babylon.max.js 2.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667
  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. * Updates the Color3 rgb values from the passed floats.
  236. * Returns the Color3.
  237. */
  238. Color3.prototype.set = function (r, g, b) {
  239. return this.copyFromFloats(r, g, b);
  240. };
  241. /**
  242. * Returns the Color3 hexadecimal code as a string.
  243. */
  244. Color3.prototype.toHexString = function () {
  245. var intR = (this.r * 255) | 0;
  246. var intG = (this.g * 255) | 0;
  247. var intB = (this.b * 255) | 0;
  248. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  249. };
  250. /**
  251. * Returns a new Color3 converted to linear space.
  252. */
  253. Color3.prototype.toLinearSpace = function () {
  254. var convertedColor = new Color3();
  255. this.toLinearSpaceToRef(convertedColor);
  256. return convertedColor;
  257. };
  258. /**
  259. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  260. * Returns the unmodified Color3.
  261. */
  262. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  263. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  264. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  265. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  266. return this;
  267. };
  268. /**
  269. * Returns a new Color3 converted to gamma space.
  270. */
  271. Color3.prototype.toGammaSpace = function () {
  272. var convertedColor = new Color3();
  273. this.toGammaSpaceToRef(convertedColor);
  274. return convertedColor;
  275. };
  276. /**
  277. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  278. * Returns the unmodified Color3.
  279. */
  280. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  281. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  282. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  283. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  284. return this;
  285. };
  286. // Statics
  287. /**
  288. * Creates a new Color3 from the string containing valid hexadecimal values.
  289. */
  290. Color3.FromHexString = function (hex) {
  291. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  292. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  293. return new Color3(0, 0, 0);
  294. }
  295. var r = parseInt(hex.substring(1, 3), 16);
  296. var g = parseInt(hex.substring(3, 5), 16);
  297. var b = parseInt(hex.substring(5, 7), 16);
  298. return Color3.FromInts(r, g, b);
  299. };
  300. /**
  301. * Creates a new Vector3 from the startind index of the passed array.
  302. */
  303. Color3.FromArray = function (array, offset) {
  304. if (offset === void 0) { offset = 0; }
  305. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  306. };
  307. /**
  308. * Creates a new Color3 from integer values ( < 256).
  309. */
  310. Color3.FromInts = function (r, g, b) {
  311. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  312. };
  313. /**
  314. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  315. */
  316. Color3.Lerp = function (start, end, amount) {
  317. var r = start.r + ((end.r - start.r) * amount);
  318. var g = start.g + ((end.g - start.g) * amount);
  319. var b = start.b + ((end.b - start.b) * amount);
  320. return new Color3(r, g, b);
  321. };
  322. Color3.Red = function () { return new Color3(1, 0, 0); };
  323. Color3.Green = function () { return new Color3(0, 1, 0); };
  324. Color3.Blue = function () { return new Color3(0, 0, 1); };
  325. Color3.Black = function () { return new Color3(0, 0, 0); };
  326. Color3.White = function () { return new Color3(1, 1, 1); };
  327. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  328. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  329. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  330. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  331. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  332. return Color3;
  333. }());
  334. BABYLON.Color3 = Color3;
  335. var Color4 = (function () {
  336. /**
  337. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  338. */
  339. function Color4(r, g, b, a) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. this.a = a;
  344. }
  345. // Operators
  346. /**
  347. * Adds in place the passed Color4 values to the current Color4.
  348. * Returns the updated Color4.
  349. */
  350. Color4.prototype.addInPlace = function (right) {
  351. this.r += right.r;
  352. this.g += right.g;
  353. this.b += right.b;
  354. this.a += right.a;
  355. return this;
  356. };
  357. /**
  358. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  359. */
  360. Color4.prototype.asArray = function () {
  361. var result = [];
  362. this.toArray(result, 0);
  363. return result;
  364. };
  365. /**
  366. * Stores from the starting index in the passed array the Color4 successive values.
  367. * Returns the Color4.
  368. */
  369. Color4.prototype.toArray = function (array, index) {
  370. if (index === undefined) {
  371. index = 0;
  372. }
  373. array[index] = this.r;
  374. array[index + 1] = this.g;
  375. array[index + 2] = this.b;
  376. array[index + 3] = this.a;
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  381. */
  382. Color4.prototype.add = function (right) {
  383. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  384. };
  385. /**
  386. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  387. */
  388. Color4.prototype.subtract = function (right) {
  389. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  390. };
  391. /**
  392. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  393. * Returns the Color4.
  394. */
  395. Color4.prototype.subtractToRef = function (right, result) {
  396. result.r = this.r - right.r;
  397. result.g = this.g - right.g;
  398. result.b = this.b - right.b;
  399. result.a = this.a - right.a;
  400. return this;
  401. };
  402. /**
  403. * Creates a new Color4 with the current Color4 values multiplied by scale.
  404. */
  405. Color4.prototype.scale = function (scale) {
  406. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  407. };
  408. /**
  409. * Multiplies the current Color4 values by scale and stores the result in "result".
  410. * Returns the Color4.
  411. */
  412. Color4.prototype.scaleToRef = function (scale, result) {
  413. result.r = this.r * scale;
  414. result.g = this.g * scale;
  415. result.b = this.b * scale;
  416. result.a = this.a * scale;
  417. return this;
  418. };
  419. /**
  420. * Multipy an RGBA Color4 value by another and return a new Color4 object
  421. * @param color The Color4 (RGBA) value to multiply by
  422. * @returns A new Color4.
  423. */
  424. Color4.prototype.multiply = function (color) {
  425. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  426. };
  427. /**
  428. * Multipy an RGBA Color4 value by another and push the result in a reference value
  429. * @param color The Color4 (RGBA) value to multiply by
  430. * @param result The Color4 (RGBA) to fill the result in
  431. * @returns the result Color4.
  432. */
  433. Color4.prototype.multiplyToRef = function (color, result) {
  434. result.r = this.r * color.r;
  435. result.g = this.g * color.g;
  436. result.b = this.b * color.b;
  437. result.a = this.a * color.a;
  438. return result;
  439. };
  440. /**
  441. * Returns a string with the Color4 values.
  442. */
  443. Color4.prototype.toString = function () {
  444. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  445. };
  446. /**
  447. * Returns the string "Color4"
  448. */
  449. Color4.prototype.getClassName = function () {
  450. return "Color4";
  451. };
  452. /**
  453. * Return the Color4 hash code as a number.
  454. */
  455. Color4.prototype.getHashCode = function () {
  456. var hash = this.r || 0;
  457. hash = (hash * 397) ^ (this.g || 0);
  458. hash = (hash * 397) ^ (this.b || 0);
  459. hash = (hash * 397) ^ (this.a || 0);
  460. return hash;
  461. };
  462. /**
  463. * Creates a new Color4 copied from the current one.
  464. */
  465. Color4.prototype.clone = function () {
  466. return new Color4(this.r, this.g, this.b, this.a);
  467. };
  468. /**
  469. * Copies the passed Color4 values into the current one.
  470. * Returns the updated Color4.
  471. */
  472. Color4.prototype.copyFrom = function (source) {
  473. this.r = source.r;
  474. this.g = source.g;
  475. this.b = source.b;
  476. this.a = source.a;
  477. return this;
  478. };
  479. /**
  480. * Copies the passed float values into the current one.
  481. * Returns the updated Color4.
  482. */
  483. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  484. this.r = r;
  485. this.g = g;
  486. this.b = b;
  487. this.a = a;
  488. return this;
  489. };
  490. /**
  491. * Copies the passed float values into the current one.
  492. * Returns the updated Color4.
  493. */
  494. Color4.prototype.set = function (r, g, b, a) {
  495. return this.copyFromFloats(r, g, b, a);
  496. };
  497. /**
  498. * Returns a string containing the hexadecimal Color4 code.
  499. */
  500. Color4.prototype.toHexString = function () {
  501. var intR = (this.r * 255) | 0;
  502. var intG = (this.g * 255) | 0;
  503. var intB = (this.b * 255) | 0;
  504. var intA = (this.a * 255) | 0;
  505. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  506. };
  507. // Statics
  508. /**
  509. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  510. */
  511. Color4.FromHexString = function (hex) {
  512. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  513. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  514. return new Color4(0.0, 0.0, 0.0, 0.0);
  515. }
  516. var r = parseInt(hex.substring(1, 3), 16);
  517. var g = parseInt(hex.substring(3, 5), 16);
  518. var b = parseInt(hex.substring(5, 7), 16);
  519. var a = parseInt(hex.substring(7, 9), 16);
  520. return Color4.FromInts(r, g, b, a);
  521. };
  522. /**
  523. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  524. */
  525. Color4.Lerp = function (left, right, amount) {
  526. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  527. Color4.LerpToRef(left, right, amount, result);
  528. return result;
  529. };
  530. /**
  531. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  532. */
  533. Color4.LerpToRef = function (left, right, amount, result) {
  534. result.r = left.r + (right.r - left.r) * amount;
  535. result.g = left.g + (right.g - left.g) * amount;
  536. result.b = left.b + (right.b - left.b) * amount;
  537. result.a = left.a + (right.a - left.a) * amount;
  538. };
  539. /**
  540. * Creates a new Color4 from the starting index element of the passed array.
  541. */
  542. Color4.FromArray = function (array, offset) {
  543. if (offset === void 0) { offset = 0; }
  544. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  545. };
  546. /**
  547. * Creates a new Color4 from the passed integers ( < 256 ).
  548. */
  549. Color4.FromInts = function (r, g, b, a) {
  550. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  551. };
  552. Color4.CheckColors4 = function (colors, count) {
  553. // Check if color3 was used
  554. if (colors.length === count * 3) {
  555. var colors4 = [];
  556. for (var index = 0; index < colors.length; index += 3) {
  557. var newIndex = (index / 3) * 4;
  558. colors4[newIndex] = colors[index];
  559. colors4[newIndex + 1] = colors[index + 1];
  560. colors4[newIndex + 2] = colors[index + 2];
  561. colors4[newIndex + 3] = 1.0;
  562. }
  563. return colors4;
  564. }
  565. return colors;
  566. };
  567. return Color4;
  568. }());
  569. BABYLON.Color4 = Color4;
  570. var Vector2 = (function () {
  571. /**
  572. * Creates a new Vector2 from the passed x and y coordinates.
  573. */
  574. function Vector2(x, y) {
  575. this.x = x;
  576. this.y = y;
  577. }
  578. /**
  579. * Returns a string with the Vector2 coordinates.
  580. */
  581. Vector2.prototype.toString = function () {
  582. return "{X: " + this.x + " Y:" + this.y + "}";
  583. };
  584. /**
  585. * Returns the string "Vector2"
  586. */
  587. Vector2.prototype.getClassName = function () {
  588. return "Vector2";
  589. };
  590. /**
  591. * Returns the Vector2 hash code as a number.
  592. */
  593. Vector2.prototype.getHashCode = function () {
  594. var hash = this.x || 0;
  595. hash = (hash * 397) ^ (this.y || 0);
  596. return hash;
  597. };
  598. // Operators
  599. /**
  600. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  601. * Returns the Vector2.
  602. */
  603. Vector2.prototype.toArray = function (array, index) {
  604. if (index === void 0) { index = 0; }
  605. array[index] = this.x;
  606. array[index + 1] = this.y;
  607. return this;
  608. };
  609. /**
  610. * Returns a new array with 2 elements : the Vector2 coordinates.
  611. */
  612. Vector2.prototype.asArray = function () {
  613. var result = [];
  614. this.toArray(result, 0);
  615. return result;
  616. };
  617. /**
  618. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  619. * Returns the updated Vector2.
  620. */
  621. Vector2.prototype.copyFrom = function (source) {
  622. this.x = source.x;
  623. this.y = source.y;
  624. return this;
  625. };
  626. /**
  627. * Sets the Vector2 coordinates with the passed floats.
  628. * Returns the updated Vector2.
  629. */
  630. Vector2.prototype.copyFromFloats = function (x, y) {
  631. this.x = x;
  632. this.y = y;
  633. return this;
  634. };
  635. /**
  636. * Sets the Vector2 coordinates with the passed floats.
  637. * Returns the updated Vector2.
  638. */
  639. Vector2.prototype.set = function (x, y) {
  640. return this.copyFromFloats(x, y);
  641. };
  642. /**
  643. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  644. */
  645. Vector2.prototype.add = function (otherVector) {
  646. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  647. };
  648. /**
  649. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  650. * Returns the Vector2.
  651. */
  652. Vector2.prototype.addToRef = function (otherVector, result) {
  653. result.x = this.x + otherVector.x;
  654. result.y = this.y + otherVector.y;
  655. return this;
  656. };
  657. /**
  658. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  659. * Returns the updated Vector2.
  660. */
  661. Vector2.prototype.addInPlace = function (otherVector) {
  662. this.x += otherVector.x;
  663. this.y += otherVector.y;
  664. return this;
  665. };
  666. /**
  667. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  668. */
  669. Vector2.prototype.addVector3 = function (otherVector) {
  670. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  671. };
  672. /**
  673. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  674. */
  675. Vector2.prototype.subtract = function (otherVector) {
  676. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  677. };
  678. /**
  679. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  680. * Returns the Vector2.
  681. */
  682. Vector2.prototype.subtractToRef = function (otherVector, result) {
  683. result.x = this.x - otherVector.x;
  684. result.y = this.y - otherVector.y;
  685. return this;
  686. };
  687. /**
  688. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  689. * Returns the updated Vector2.
  690. */
  691. Vector2.prototype.subtractInPlace = function (otherVector) {
  692. this.x -= otherVector.x;
  693. this.y -= otherVector.y;
  694. return this;
  695. };
  696. /**
  697. * Multiplies in place the current Vector2 coordinates by the passed ones.
  698. * Returns the updated Vector2.
  699. */
  700. Vector2.prototype.multiplyInPlace = function (otherVector) {
  701. this.x *= otherVector.x;
  702. this.y *= otherVector.y;
  703. return this;
  704. };
  705. /**
  706. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  707. */
  708. Vector2.prototype.multiply = function (otherVector) {
  709. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  710. };
  711. /**
  712. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  713. * Returns the Vector2.
  714. */
  715. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  716. result.x = this.x * otherVector.x;
  717. result.y = this.y * otherVector.y;
  718. return this;
  719. };
  720. /**
  721. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  722. */
  723. Vector2.prototype.multiplyByFloats = function (x, y) {
  724. return new Vector2(this.x * x, this.y * y);
  725. };
  726. /**
  727. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  728. */
  729. Vector2.prototype.divide = function (otherVector) {
  730. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  731. };
  732. /**
  733. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  734. * Returns the Vector2.
  735. */
  736. Vector2.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. return this;
  740. };
  741. /**
  742. * Returns a new Vector2 with current Vector2 negated coordinates.
  743. */
  744. Vector2.prototype.negate = function () {
  745. return new Vector2(-this.x, -this.y);
  746. };
  747. /**
  748. * Multiply the Vector2 coordinates by scale.
  749. * Returns the updated Vector2.
  750. */
  751. Vector2.prototype.scaleInPlace = function (scale) {
  752. this.x *= scale;
  753. this.y *= scale;
  754. return this;
  755. };
  756. /**
  757. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  758. */
  759. Vector2.prototype.scale = function (scale) {
  760. return new Vector2(this.x * scale, this.y * scale);
  761. };
  762. /**
  763. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  764. */
  765. Vector2.prototype.equals = function (otherVector) {
  766. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  767. };
  768. /**
  769. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  770. */
  771. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  772. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  773. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  774. };
  775. // Properties
  776. /**
  777. * Returns the vector length (float).
  778. */
  779. Vector2.prototype.length = function () {
  780. return Math.sqrt(this.x * this.x + this.y * this.y);
  781. };
  782. /**
  783. * Returns the vector squared length (float);
  784. */
  785. Vector2.prototype.lengthSquared = function () {
  786. return (this.x * this.x + this.y * this.y);
  787. };
  788. // Methods
  789. /**
  790. * Normalize the vector.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.normalize = function () {
  794. var len = this.length();
  795. if (len === 0)
  796. return this;
  797. var num = 1.0 / len;
  798. this.x *= num;
  799. this.y *= num;
  800. return this;
  801. };
  802. /**
  803. * Returns a new Vector2 copied from the Vector2.
  804. */
  805. Vector2.prototype.clone = function () {
  806. return new Vector2(this.x, this.y);
  807. };
  808. // Statics
  809. /**
  810. * Returns a new Vector2(0, 0)
  811. */
  812. Vector2.Zero = function () {
  813. return new Vector2(0, 0);
  814. };
  815. /**
  816. * Returns a new Vector2 set from the passed index element of the passed array or Float32Array.
  817. */
  818. Vector2.FromArray = function (array, offset) {
  819. if (offset === void 0) { offset = 0; }
  820. return new Vector2(array[offset], array[offset + 1]);
  821. };
  822. /**
  823. * Sets "result" from the passed index element of the passed array or Float32Array.
  824. * Returns the Vector2.
  825. */
  826. Vector2.FromArrayToRef = function (array, offset, result) {
  827. result.x = array[offset];
  828. result.y = array[offset + 1];
  829. };
  830. /**
  831. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  832. */
  833. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  834. var squared = amount * amount;
  835. var cubed = amount * squared;
  836. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  837. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  838. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  839. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  840. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  841. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  842. return new Vector2(x, y);
  843. };
  844. /**
  845. * 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".
  846. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  847. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  848. */
  849. Vector2.Clamp = function (value, min, max) {
  850. var x = value.x;
  851. x = (x > max.x) ? max.x : x;
  852. x = (x < min.x) ? min.x : x;
  853. var y = value.y;
  854. y = (y > max.y) ? max.y : y;
  855. y = (y < min.y) ? min.y : y;
  856. return new Vector2(x, y);
  857. };
  858. /**
  859. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  860. */
  861. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  862. var squared = amount * amount;
  863. var cubed = amount * squared;
  864. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  865. var part2 = (-2.0 * cubed) + (3.0 * squared);
  866. var part3 = (cubed - (2.0 * squared)) + amount;
  867. var part4 = cubed - squared;
  868. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  869. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  870. return new Vector2(x, y);
  871. };
  872. /**
  873. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  874. */
  875. Vector2.Lerp = function (start, end, amount) {
  876. var x = start.x + ((end.x - start.x) * amount);
  877. var y = start.y + ((end.y - start.y) * amount);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns the dot product (float) of the vector "left" and the vector "right".
  882. */
  883. Vector2.Dot = function (left, right) {
  884. return left.x * right.x + left.y * right.y;
  885. };
  886. /**
  887. * Returns a new Vector2 equal to the normalized passed vector.
  888. */
  889. Vector2.Normalize = function (vector) {
  890. var newVector = vector.clone();
  891. newVector.normalize();
  892. return newVector;
  893. };
  894. /**
  895. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  896. */
  897. Vector2.Minimize = function (left, right) {
  898. var x = (left.x < right.x) ? left.x : right.x;
  899. var y = (left.y < right.y) ? left.y : right.y;
  900. return new Vector2(x, y);
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Maximize = function (left, right) {
  906. var x = (left.x > right.x) ? left.x : right.x;
  907. var y = (left.y > right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  912. */
  913. Vector2.Transform = function (vector, transformation) {
  914. var r = Vector2.Zero();
  915. Vector2.TransformToRef(vector, transformation, r);
  916. return r;
  917. };
  918. /**
  919. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  920. */
  921. Vector2.TransformToRef = function (vector, transformation, result) {
  922. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  923. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  924. result.x = x;
  925. result.y = y;
  926. };
  927. /**
  928. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  929. */
  930. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  931. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  932. var sign = a < 0 ? -1 : 1;
  933. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  934. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  935. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  936. };
  937. /**
  938. * Returns the distance (float) between the vectors "value1" and "value2".
  939. */
  940. Vector2.Distance = function (value1, value2) {
  941. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  942. };
  943. /**
  944. * Returns the squared distance (float) between the vectors "value1" and "value2".
  945. */
  946. Vector2.DistanceSquared = function (value1, value2) {
  947. var x = value1.x - value2.x;
  948. var y = value1.y - value2.y;
  949. return (x * x) + (y * y);
  950. };
  951. /**
  952. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  953. */
  954. Vector2.Center = function (value1, value2) {
  955. var center = value1.add(value2);
  956. center.scaleInPlace(0.5);
  957. return center;
  958. };
  959. /**
  960. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  961. */
  962. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  963. var l2 = Vector2.DistanceSquared(segA, segB);
  964. if (l2 === 0.0) {
  965. return Vector2.Distance(p, segA);
  966. }
  967. var v = segB.subtract(segA);
  968. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  969. var proj = segA.add(v.multiplyByFloats(t, t));
  970. return Vector2.Distance(p, proj);
  971. };
  972. return Vector2;
  973. }());
  974. BABYLON.Vector2 = Vector2;
  975. var Vector3 = (function () {
  976. /**
  977. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  978. * A Vector3 is the main object used in 3D geometry.
  979. * It can represent etiher the coordinates of a point the space, either a direction.
  980. */
  981. function Vector3(x, y, z) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. }
  986. /**
  987. * Returns a string with the Vector3 coordinates.
  988. */
  989. Vector3.prototype.toString = function () {
  990. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  991. };
  992. /**
  993. * Returns the string "Vector3"
  994. */
  995. Vector3.prototype.getClassName = function () {
  996. return "Vector3";
  997. };
  998. /**
  999. * Returns the Vector hash code.
  1000. */
  1001. Vector3.prototype.getHashCode = function () {
  1002. var hash = this.x || 0;
  1003. hash = (hash * 397) ^ (this.y || 0);
  1004. hash = (hash * 397) ^ (this.z || 0);
  1005. return hash;
  1006. };
  1007. // Operators
  1008. /**
  1009. * Returns a new array with three elements : the coordinates the Vector3.
  1010. */
  1011. Vector3.prototype.asArray = function () {
  1012. var result = [];
  1013. this.toArray(result, 0);
  1014. return result;
  1015. };
  1016. /**
  1017. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1018. * Returns the Vector3.
  1019. */
  1020. Vector3.prototype.toArray = function (array, index) {
  1021. if (index === void 0) { index = 0; }
  1022. array[index] = this.x;
  1023. array[index + 1] = this.y;
  1024. array[index + 2] = this.z;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1029. */
  1030. Vector3.prototype.toQuaternion = function () {
  1031. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1032. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1033. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1034. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1035. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1036. var cosy = Math.cos(this.y * 0.5);
  1037. var siny = Math.sin(this.y * 0.5);
  1038. result.x = coszMinusx * siny;
  1039. result.y = -sinzMinusx * siny;
  1040. result.z = sinxPlusz * cosy;
  1041. result.w = cosxPlusz * cosy;
  1042. return result;
  1043. };
  1044. /**
  1045. * Adds the passed vector to the current Vector3.
  1046. * Returns the updated Vector3.
  1047. */
  1048. Vector3.prototype.addInPlace = function (otherVector) {
  1049. this.x += otherVector.x;
  1050. this.y += otherVector.y;
  1051. this.z += otherVector.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1056. */
  1057. Vector3.prototype.add = function (otherVector) {
  1058. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1059. };
  1060. /**
  1061. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1062. * Returns the current Vector3.
  1063. */
  1064. Vector3.prototype.addToRef = function (otherVector, result) {
  1065. result.x = this.x + otherVector.x;
  1066. result.y = this.y + otherVector.y;
  1067. result.z = this.z + otherVector.z;
  1068. return this;
  1069. };
  1070. /**
  1071. * Subtract the passed vector from the current Vector3.
  1072. * Returns the updated Vector3.
  1073. */
  1074. Vector3.prototype.subtractInPlace = function (otherVector) {
  1075. this.x -= otherVector.x;
  1076. this.y -= otherVector.y;
  1077. this.z -= otherVector.z;
  1078. return this;
  1079. };
  1080. /**
  1081. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1082. */
  1083. Vector3.prototype.subtract = function (otherVector) {
  1084. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1085. };
  1086. /**
  1087. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1088. * Returns the current Vector3.
  1089. */
  1090. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1091. result.x = this.x - otherVector.x;
  1092. result.y = this.y - otherVector.y;
  1093. result.z = this.z - otherVector.z;
  1094. return this;
  1095. };
  1096. /**
  1097. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1098. */
  1099. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1100. return new Vector3(this.x - x, this.y - y, this.z - z);
  1101. };
  1102. /**
  1103. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1104. * Returns the current Vector3.
  1105. */
  1106. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1107. result.x = this.x - x;
  1108. result.y = this.y - y;
  1109. result.z = this.z - z;
  1110. return this;
  1111. };
  1112. /**
  1113. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1114. */
  1115. Vector3.prototype.negate = function () {
  1116. return new Vector3(-this.x, -this.y, -this.z);
  1117. };
  1118. /**
  1119. * Multiplies the Vector3 coordinates by the float "scale".
  1120. * Returns the updated Vector3.
  1121. */
  1122. Vector3.prototype.scaleInPlace = function (scale) {
  1123. this.x *= scale;
  1124. this.y *= scale;
  1125. this.z *= scale;
  1126. return this;
  1127. };
  1128. /**
  1129. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1130. */
  1131. Vector3.prototype.scale = function (scale) {
  1132. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1133. };
  1134. /**
  1135. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1136. * Returns the current Vector3.
  1137. */
  1138. Vector3.prototype.scaleToRef = function (scale, result) {
  1139. result.x = this.x * scale;
  1140. result.y = this.y * scale;
  1141. result.z = this.z * scale;
  1142. return this;
  1143. };
  1144. /**
  1145. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1146. */
  1147. Vector3.prototype.equals = function (otherVector) {
  1148. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1149. };
  1150. /**
  1151. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1152. */
  1153. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1154. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1155. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1156. };
  1157. /**
  1158. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1159. */
  1160. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1161. return this.x === x && this.y === y && this.z === z;
  1162. };
  1163. /**
  1164. * Muliplies the current Vector3 coordinates by the passed ones.
  1165. * Returns the updated Vector3.
  1166. */
  1167. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1168. this.x *= otherVector.x;
  1169. this.y *= otherVector.y;
  1170. this.z *= otherVector.z;
  1171. return this;
  1172. };
  1173. /**
  1174. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1175. */
  1176. Vector3.prototype.multiply = function (otherVector) {
  1177. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1178. };
  1179. /**
  1180. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1181. * Returns the current Vector3.
  1182. */
  1183. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1184. result.x = this.x * otherVector.x;
  1185. result.y = this.y * otherVector.y;
  1186. result.z = this.z * otherVector.z;
  1187. return this;
  1188. };
  1189. /**
  1190. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1191. */
  1192. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1193. return new Vector3(this.x * x, this.y * y, this.z * z);
  1194. };
  1195. /**
  1196. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1197. */
  1198. Vector3.prototype.divide = function (otherVector) {
  1199. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1200. };
  1201. /**
  1202. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1203. * Returns the current Vector3.
  1204. */
  1205. Vector3.prototype.divideToRef = function (otherVector, result) {
  1206. result.x = this.x / otherVector.x;
  1207. result.y = this.y / otherVector.y;
  1208. result.z = this.z / otherVector.z;
  1209. return this;
  1210. };
  1211. /**
  1212. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1213. * Returns the updated Vector3.
  1214. */
  1215. Vector3.prototype.MinimizeInPlace = function (other) {
  1216. if (other.x < this.x)
  1217. this.x = other.x;
  1218. if (other.y < this.y)
  1219. this.y = other.y;
  1220. if (other.z < this.z)
  1221. this.z = other.z;
  1222. return this;
  1223. };
  1224. /**
  1225. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1226. * Returns the updated Vector3.
  1227. */
  1228. Vector3.prototype.MaximizeInPlace = function (other) {
  1229. if (other.x > this.x)
  1230. this.x = other.x;
  1231. if (other.y > this.y)
  1232. this.y = other.y;
  1233. if (other.z > this.z)
  1234. this.z = other.z;
  1235. return this;
  1236. };
  1237. // Properties
  1238. /**
  1239. * Returns the length of the Vector3 (float).
  1240. */
  1241. Vector3.prototype.length = function () {
  1242. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1243. };
  1244. /**
  1245. * Returns the squared length of the Vector3 (float).
  1246. */
  1247. Vector3.prototype.lengthSquared = function () {
  1248. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1249. };
  1250. // Methods
  1251. /**
  1252. * Normalize the current Vector3.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.normalize = function () {
  1256. var len = this.length();
  1257. if (len === 0 || len === 1.0)
  1258. return this;
  1259. var num = 1.0 / len;
  1260. this.x *= num;
  1261. this.y *= num;
  1262. this.z *= num;
  1263. return this;
  1264. };
  1265. /**
  1266. * Returns a new Vector3 copied from the current Vector3.
  1267. */
  1268. Vector3.prototype.clone = function () {
  1269. return new Vector3(this.x, this.y, this.z);
  1270. };
  1271. /**
  1272. * Copies the passed vector coordinates to the current Vector3 ones.
  1273. * Returns the updated Vector3.
  1274. */
  1275. Vector3.prototype.copyFrom = function (source) {
  1276. this.x = source.x;
  1277. this.y = source.y;
  1278. this.z = source.z;
  1279. return this;
  1280. };
  1281. /**
  1282. * Copies the passed floats to the current Vector3 coordinates.
  1283. * Returns the updated Vector3.
  1284. */
  1285. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1286. this.x = x;
  1287. this.y = y;
  1288. this.z = z;
  1289. return this;
  1290. };
  1291. /**
  1292. * Copies the passed floats to the current Vector3 coordinates.
  1293. * Returns the updated Vector3.
  1294. */
  1295. Vector3.prototype.set = function (x, y, z) {
  1296. return this.copyFromFloats(x, y, z);
  1297. };
  1298. // Statics
  1299. /**
  1300. *
  1301. */
  1302. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1303. var d0 = Vector3.Dot(vector0, axis) - size;
  1304. var d1 = Vector3.Dot(vector1, axis) - size;
  1305. var s = d0 / (d0 - d1);
  1306. return s;
  1307. };
  1308. /**
  1309. * Returns a new Vector3 set from the index "offset" of the passed array or Float32Array.
  1310. */
  1311. Vector3.FromArray = function (array, offset) {
  1312. if (!offset) {
  1313. offset = 0;
  1314. }
  1315. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1316. };
  1317. /**
  1318. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1319. */
  1320. Vector3.FromFloatArray = function (array, offset) {
  1321. if (!offset) {
  1322. offset = 0;
  1323. }
  1324. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1325. };
  1326. /**
  1327. * Sets the passed vector "result" with the element values from the index "offset" of the passed array or Float32Array.
  1328. */
  1329. Vector3.FromArrayToRef = function (array, offset, result) {
  1330. result.x = array[offset];
  1331. result.y = array[offset + 1];
  1332. result.z = array[offset + 2];
  1333. };
  1334. /**
  1335. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1336. */
  1337. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. };
  1342. /**
  1343. * Sets the passed vector "result" with the passed floats.
  1344. */
  1345. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1346. result.x = x;
  1347. result.y = y;
  1348. result.z = z;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1352. */
  1353. Vector3.Zero = function () {
  1354. return new Vector3(0.0, 0.0, 0.0);
  1355. };
  1356. /**
  1357. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1358. */
  1359. Vector3.Up = function () {
  1360. return new Vector3(0.0, 1.0, 0.0);
  1361. };
  1362. /**
  1363. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1364. */
  1365. Vector3.Forward = function () {
  1366. return new Vector3(0.0, 0.0, 1.0);
  1367. };
  1368. /**
  1369. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1370. */
  1371. Vector3.Right = function () {
  1372. return new Vector3(1.0, 0.0, 0.0);
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1376. */
  1377. Vector3.Left = function () {
  1378. return new Vector3(-1.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1382. * This method computes tranformed coordinates only, not transformed direction vectors.
  1383. */
  1384. Vector3.TransformCoordinates = function (vector, transformation) {
  1385. var result = Vector3.Zero();
  1386. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1387. return result;
  1388. };
  1389. /**
  1390. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1391. * This method computes tranformed coordinates only, not transformed direction vectors.
  1392. */
  1393. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1394. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1395. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1396. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1397. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1398. result.x = x / w;
  1399. result.y = y / w;
  1400. result.z = z / w;
  1401. };
  1402. /**
  1403. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1404. * This method computes tranformed coordinates only, not transformed direction vectors.
  1405. */
  1406. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1407. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1408. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1409. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1410. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1411. result.x = rx / rw;
  1412. result.y = ry / rw;
  1413. result.z = rz / rw;
  1414. };
  1415. /**
  1416. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1417. * This methods computes transformed normalized direction vectors only.
  1418. */
  1419. Vector3.TransformNormal = function (vector, transformation) {
  1420. var result = Vector3.Zero();
  1421. Vector3.TransformNormalToRef(vector, transformation, result);
  1422. return result;
  1423. };
  1424. /**
  1425. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1426. * This methods computes transformed normalized direction vectors only.
  1427. */
  1428. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1429. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1430. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1431. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1432. result.x = x;
  1433. result.y = y;
  1434. result.z = z;
  1435. };
  1436. /**
  1437. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1438. * This methods computes transformed normalized direction vectors only.
  1439. */
  1440. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1441. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1442. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1443. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1444. };
  1445. /**
  1446. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1447. */
  1448. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1449. var squared = amount * amount;
  1450. var cubed = amount * squared;
  1451. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1452. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1453. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1454. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1455. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1456. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1457. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1458. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1459. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1460. return new Vector3(x, y, z);
  1461. };
  1462. /**
  1463. * 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".
  1464. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1465. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1466. */
  1467. Vector3.Clamp = function (value, min, max) {
  1468. var x = value.x;
  1469. x = (x > max.x) ? max.x : x;
  1470. x = (x < min.x) ? min.x : x;
  1471. var y = value.y;
  1472. y = (y > max.y) ? max.y : y;
  1473. y = (y < min.y) ? min.y : y;
  1474. var z = value.z;
  1475. z = (z > max.z) ? max.z : z;
  1476. z = (z < min.z) ? min.z : z;
  1477. return new Vector3(x, y, z);
  1478. };
  1479. /**
  1480. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1481. */
  1482. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1483. var squared = amount * amount;
  1484. var cubed = amount * squared;
  1485. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1486. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1487. var part3 = (cubed - (2.0 * squared)) + amount;
  1488. var part4 = cubed - squared;
  1489. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1490. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1491. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1492. return new Vector3(x, y, z);
  1493. };
  1494. /**
  1495. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1496. */
  1497. Vector3.Lerp = function (start, end, amount) {
  1498. var result = new Vector3(0, 0, 0);
  1499. Vector3.LerpToRef(start, end, amount, result);
  1500. return result;
  1501. };
  1502. /**
  1503. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1504. */
  1505. Vector3.LerpToRef = function (start, end, amount, result) {
  1506. result.x = start.x + ((end.x - start.x) * amount);
  1507. result.y = start.y + ((end.y - start.y) * amount);
  1508. result.z = start.z + ((end.z - start.z) * amount);
  1509. };
  1510. /**
  1511. * Returns the dot product (float) between the vectors "left" and "right".
  1512. */
  1513. Vector3.Dot = function (left, right) {
  1514. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1515. };
  1516. /**
  1517. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1518. * The cross product is then orthogonal to both "left" and "right".
  1519. */
  1520. Vector3.Cross = function (left, right) {
  1521. var result = Vector3.Zero();
  1522. Vector3.CrossToRef(left, right, result);
  1523. return result;
  1524. };
  1525. /**
  1526. * Sets the passed vector "result" with the cross product of "left" and "right".
  1527. * The cross product is then orthogonal to both "left" and "right".
  1528. */
  1529. Vector3.CrossToRef = function (left, right, result) {
  1530. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1531. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1532. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1533. result.copyFrom(MathTmp.Vector3[0]);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 as the normalization of the passed vector.
  1537. */
  1538. Vector3.Normalize = function (vector) {
  1539. var result = Vector3.Zero();
  1540. Vector3.NormalizeToRef(vector, result);
  1541. return result;
  1542. };
  1543. /**
  1544. * Sets the passed vector "result" with the normalization of the passed first vector.
  1545. */
  1546. Vector3.NormalizeToRef = function (vector, result) {
  1547. result.copyFrom(vector);
  1548. result.normalize();
  1549. };
  1550. Vector3.Project = function (vector, world, transform, viewport) {
  1551. var cw = viewport.width;
  1552. var ch = viewport.height;
  1553. var cx = viewport.x;
  1554. var cy = viewport.y;
  1555. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1556. 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);
  1557. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1558. world.multiplyToRef(transform, matrix);
  1559. matrix.multiplyToRef(viewportMatrix, matrix);
  1560. return Vector3.TransformCoordinates(vector, matrix);
  1561. };
  1562. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1563. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1564. world.multiplyToRef(transform, matrix);
  1565. matrix.invert();
  1566. source.x = source.x / viewportWidth * 2 - 1;
  1567. source.y = -(source.y / viewportHeight * 2 - 1);
  1568. var vector = Vector3.TransformCoordinates(source, matrix);
  1569. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1570. if (MathTools.WithinEpsilon(num, 1.0)) {
  1571. vector = vector.scale(1.0 / num);
  1572. }
  1573. return vector;
  1574. };
  1575. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1576. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1577. world.multiplyToRef(view, matrix);
  1578. matrix.multiplyToRef(projection, matrix);
  1579. matrix.invert();
  1580. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1581. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1582. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1583. if (MathTools.WithinEpsilon(num, 1.0)) {
  1584. vector = vector.scale(1.0 / num);
  1585. }
  1586. return vector;
  1587. };
  1588. Vector3.Minimize = function (left, right) {
  1589. var min = left.clone();
  1590. min.MinimizeInPlace(right);
  1591. return min;
  1592. };
  1593. Vector3.Maximize = function (left, right) {
  1594. var max = left.clone();
  1595. max.MaximizeInPlace(right);
  1596. return max;
  1597. };
  1598. /**
  1599. * Returns the distance (float) between the vectors "value1" and "value2".
  1600. */
  1601. Vector3.Distance = function (value1, value2) {
  1602. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1603. };
  1604. /**
  1605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1606. */
  1607. Vector3.DistanceSquared = function (value1, value2) {
  1608. var x = value1.x - value2.x;
  1609. var y = value1.y - value2.y;
  1610. var z = value1.z - value2.z;
  1611. return (x * x) + (y * y) + (z * z);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 located at the center between "value1" and "value2".
  1615. */
  1616. Vector3.Center = function (value1, value2) {
  1617. var center = value1.add(value2);
  1618. center.scaleInPlace(0.5);
  1619. return center;
  1620. };
  1621. /**
  1622. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1623. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1624. * to something in order to rotate it from its local system to the given target system.
  1625. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1626. * Returns a new Vector3.
  1627. */
  1628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1629. var rotation = Vector3.Zero();
  1630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1631. return rotation;
  1632. };
  1633. /**
  1634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1635. */
  1636. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1637. var quat = MathTmp.Quaternion[0];
  1638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1639. quat.toEulerAnglesToRef(ref);
  1640. };
  1641. return Vector3;
  1642. }());
  1643. BABYLON.Vector3 = Vector3;
  1644. //Vector4 class created for EulerAngle class conversion to Quaternion
  1645. var Vector4 = (function () {
  1646. /**
  1647. * Creates a Vector4 object from the passed floats.
  1648. */
  1649. function Vector4(x, y, z, w) {
  1650. this.x = x;
  1651. this.y = y;
  1652. this.z = z;
  1653. this.w = w;
  1654. }
  1655. /**
  1656. * Returns the string with the Vector4 coordinates.
  1657. */
  1658. Vector4.prototype.toString = function () {
  1659. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1660. };
  1661. /**
  1662. * Returns the string "Vector4".
  1663. */
  1664. Vector4.prototype.getClassName = function () {
  1665. return "Vector4";
  1666. };
  1667. /**
  1668. * Returns the Vector4 hash code.
  1669. */
  1670. Vector4.prototype.getHashCode = function () {
  1671. var hash = this.x || 0;
  1672. hash = (hash * 397) ^ (this.y || 0);
  1673. hash = (hash * 397) ^ (this.z || 0);
  1674. hash = (hash * 397) ^ (this.w || 0);
  1675. return hash;
  1676. };
  1677. // Operators
  1678. /**
  1679. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1680. */
  1681. Vector4.prototype.asArray = function () {
  1682. var result = [];
  1683. this.toArray(result, 0);
  1684. return result;
  1685. };
  1686. /**
  1687. * Populates the passed array from the passed index with the Vector4 coordinates.
  1688. * Returns the Vector4.
  1689. */
  1690. Vector4.prototype.toArray = function (array, index) {
  1691. if (index === undefined) {
  1692. index = 0;
  1693. }
  1694. array[index] = this.x;
  1695. array[index + 1] = this.y;
  1696. array[index + 2] = this.z;
  1697. array[index + 3] = this.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Adds the passed vector to the current Vector4.
  1702. * Returns the updated Vector4.
  1703. */
  1704. Vector4.prototype.addInPlace = function (otherVector) {
  1705. this.x += otherVector.x;
  1706. this.y += otherVector.y;
  1707. this.z += otherVector.z;
  1708. this.w += otherVector.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1713. */
  1714. Vector4.prototype.add = function (otherVector) {
  1715. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1716. };
  1717. /**
  1718. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1719. * Returns the current Vector4.
  1720. */
  1721. Vector4.prototype.addToRef = function (otherVector, result) {
  1722. result.x = this.x + otherVector.x;
  1723. result.y = this.y + otherVector.y;
  1724. result.z = this.z + otherVector.z;
  1725. result.w = this.w + otherVector.w;
  1726. return this;
  1727. };
  1728. /**
  1729. * Subtract in place the passed vector from the current Vector4.
  1730. * Returns the updated Vector4.
  1731. */
  1732. Vector4.prototype.subtractInPlace = function (otherVector) {
  1733. this.x -= otherVector.x;
  1734. this.y -= otherVector.y;
  1735. this.z -= otherVector.z;
  1736. this.w -= otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1741. */
  1742. Vector4.prototype.subtract = function (otherVector) {
  1743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1744. };
  1745. /**
  1746. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1747. * Returns the current Vector4.
  1748. */
  1749. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1750. result.x = this.x - otherVector.x;
  1751. result.y = this.y - otherVector.y;
  1752. result.z = this.z - otherVector.z;
  1753. result.w = this.w - otherVector.w;
  1754. return this;
  1755. };
  1756. /**
  1757. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1758. */
  1759. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1760. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1761. };
  1762. /**
  1763. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1764. * Returns the current Vector4.
  1765. */
  1766. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1767. result.x = this.x - x;
  1768. result.y = this.y - y;
  1769. result.z = this.z - z;
  1770. result.w = this.w - w;
  1771. return this;
  1772. };
  1773. /**
  1774. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1775. */
  1776. Vector4.prototype.negate = function () {
  1777. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1778. };
  1779. /**
  1780. * Multiplies the current Vector4 coordinates by scale (float).
  1781. * Returns the updated Vector4.
  1782. */
  1783. Vector4.prototype.scaleInPlace = function (scale) {
  1784. this.x *= scale;
  1785. this.y *= scale;
  1786. this.z *= scale;
  1787. this.w *= scale;
  1788. return this;
  1789. };
  1790. /**
  1791. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1792. */
  1793. Vector4.prototype.scale = function (scale) {
  1794. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1795. };
  1796. /**
  1797. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1798. * Returns the current Vector4.
  1799. */
  1800. Vector4.prototype.scaleToRef = function (scale, result) {
  1801. result.x = this.x * scale;
  1802. result.y = this.y * scale;
  1803. result.z = this.z * scale;
  1804. result.w = this.w * scale;
  1805. return this;
  1806. };
  1807. /**
  1808. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1809. */
  1810. Vector4.prototype.equals = function (otherVector) {
  1811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1812. };
  1813. /**
  1814. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1815. */
  1816. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1817. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1818. return otherVector
  1819. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1820. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1821. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1822. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1823. };
  1824. /**
  1825. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1826. */
  1827. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1828. return this.x === x && this.y === y && this.z === z && this.w === w;
  1829. };
  1830. /**
  1831. * Multiplies in place the current Vector4 by the passed one.
  1832. * Returns the updated Vector4.
  1833. */
  1834. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1835. this.x *= otherVector.x;
  1836. this.y *= otherVector.y;
  1837. this.z *= otherVector.z;
  1838. this.w *= otherVector.w;
  1839. return this;
  1840. };
  1841. /**
  1842. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1843. */
  1844. Vector4.prototype.multiply = function (otherVector) {
  1845. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1846. };
  1847. /**
  1848. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1849. * Returns the current Vector4.
  1850. */
  1851. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1852. result.x = this.x * otherVector.x;
  1853. result.y = this.y * otherVector.y;
  1854. result.z = this.z * otherVector.z;
  1855. result.w = this.w * otherVector.w;
  1856. return this;
  1857. };
  1858. /**
  1859. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1860. */
  1861. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1862. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1863. };
  1864. /**
  1865. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1866. */
  1867. Vector4.prototype.divide = function (otherVector) {
  1868. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1869. };
  1870. /**
  1871. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1872. * Returns the current Vector4.
  1873. */
  1874. Vector4.prototype.divideToRef = function (otherVector, result) {
  1875. result.x = this.x / otherVector.x;
  1876. result.y = this.y / otherVector.y;
  1877. result.z = this.z / otherVector.z;
  1878. result.w = this.w / otherVector.w;
  1879. return this;
  1880. };
  1881. /**
  1882. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1883. */
  1884. Vector4.prototype.MinimizeInPlace = function (other) {
  1885. if (other.x < this.x)
  1886. this.x = other.x;
  1887. if (other.y < this.y)
  1888. this.y = other.y;
  1889. if (other.z < this.z)
  1890. this.z = other.z;
  1891. if (other.w < this.w)
  1892. this.w = other.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1897. */
  1898. Vector4.prototype.MaximizeInPlace = function (other) {
  1899. if (other.x > this.x)
  1900. this.x = other.x;
  1901. if (other.y > this.y)
  1902. this.y = other.y;
  1903. if (other.z > this.z)
  1904. this.z = other.z;
  1905. if (other.w > this.w)
  1906. this.w = other.w;
  1907. return this;
  1908. };
  1909. // Properties
  1910. /**
  1911. * Returns the Vector4 length (float).
  1912. */
  1913. Vector4.prototype.length = function () {
  1914. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1915. };
  1916. /**
  1917. * Returns the Vector4 squared length (float).
  1918. */
  1919. Vector4.prototype.lengthSquared = function () {
  1920. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1921. };
  1922. // Methods
  1923. /**
  1924. * Normalizes in place the Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.normalize = function () {
  1928. var len = this.length();
  1929. if (len === 0)
  1930. return this;
  1931. var num = 1.0 / len;
  1932. this.x *= num;
  1933. this.y *= num;
  1934. this.z *= num;
  1935. this.w *= num;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1940. */
  1941. Vector4.prototype.toVector3 = function () {
  1942. return new Vector3(this.x, this.y, this.z);
  1943. };
  1944. /**
  1945. * Returns a new Vector4 copied from the current one.
  1946. */
  1947. Vector4.prototype.clone = function () {
  1948. return new Vector4(this.x, this.y, this.z, this.w);
  1949. };
  1950. /**
  1951. * Updates the current Vector4 with the passed one coordinates.
  1952. * Returns the updated Vector4.
  1953. */
  1954. Vector4.prototype.copyFrom = function (source) {
  1955. this.x = source.x;
  1956. this.y = source.y;
  1957. this.z = source.z;
  1958. this.w = source.w;
  1959. return this;
  1960. };
  1961. /**
  1962. * Updates the current Vector4 coordinates with the passed floats.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1966. this.x = x;
  1967. this.y = y;
  1968. this.z = z;
  1969. this.w = w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.set = function (x, y, z, w) {
  1977. return this.copyFromFloats(x, y, z, w);
  1978. };
  1979. // Statics
  1980. /**
  1981. * Returns a new Vector4 set from the starting index of the passed array.
  1982. */
  1983. Vector4.FromArray = function (array, offset) {
  1984. if (!offset) {
  1985. offset = 0;
  1986. }
  1987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1988. };
  1989. /**
  1990. * Updates the passed vector "result" from the starting index of the passed array.
  1991. */
  1992. Vector4.FromArrayToRef = function (array, offset, result) {
  1993. result.x = array[offset];
  1994. result.y = array[offset + 1];
  1995. result.z = array[offset + 2];
  1996. result.w = array[offset + 3];
  1997. };
  1998. /**
  1999. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2000. */
  2001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2002. result.x = array[offset];
  2003. result.y = array[offset + 1];
  2004. result.z = array[offset + 2];
  2005. result.w = array[offset + 3];
  2006. };
  2007. /**
  2008. * Updates the passed vector "result" coordinates from the passed floats.
  2009. */
  2010. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2011. result.x = x;
  2012. result.y = y;
  2013. result.z = z;
  2014. result.w = w;
  2015. };
  2016. /**
  2017. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2018. */
  2019. Vector4.Zero = function () {
  2020. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2021. };
  2022. /**
  2023. * Returns a new normalized Vector4 from the passed one.
  2024. */
  2025. Vector4.Normalize = function (vector) {
  2026. var result = Vector4.Zero();
  2027. Vector4.NormalizeToRef(vector, result);
  2028. return result;
  2029. };
  2030. /**
  2031. * Updates the passed vector "result" from the normalization of the passed one.
  2032. */
  2033. Vector4.NormalizeToRef = function (vector, result) {
  2034. result.copyFrom(vector);
  2035. result.normalize();
  2036. };
  2037. Vector4.Minimize = function (left, right) {
  2038. var min = left.clone();
  2039. min.MinimizeInPlace(right);
  2040. return min;
  2041. };
  2042. Vector4.Maximize = function (left, right) {
  2043. var max = left.clone();
  2044. max.MaximizeInPlace(right);
  2045. return max;
  2046. };
  2047. /**
  2048. * Returns the distance (float) between the vectors "value1" and "value2".
  2049. */
  2050. Vector4.Distance = function (value1, value2) {
  2051. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2052. };
  2053. Vector4.DistanceSquared = function (value1, value2) {
  2054. var x = value1.x - value2.x;
  2055. var y = value1.y - value2.y;
  2056. var z = value1.z - value2.z;
  2057. var w = value1.w - value2.w;
  2058. return (x * x) + (y * y) + (z * z) + (w * w);
  2059. };
  2060. /**
  2061. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2062. */
  2063. Vector4.Center = function (value1, value2) {
  2064. var center = value1.add(value2);
  2065. center.scaleInPlace(0.5);
  2066. return center;
  2067. };
  2068. return Vector4;
  2069. }());
  2070. BABYLON.Vector4 = Vector4;
  2071. var Size = (function () {
  2072. /**
  2073. * Creates a Size object from the passed width and height (floats).
  2074. */
  2075. function Size(width, height) {
  2076. this.width = width;
  2077. this.height = height;
  2078. }
  2079. // Returns a string with the Size width and height.
  2080. Size.prototype.toString = function () {
  2081. return "{W: " + this.width + ", H: " + this.height + "}";
  2082. };
  2083. /**
  2084. * Returns the string "Size"
  2085. */
  2086. Size.prototype.getClassName = function () {
  2087. return "Size";
  2088. };
  2089. /**
  2090. * Returns the Size hash code.
  2091. */
  2092. Size.prototype.getHashCode = function () {
  2093. var hash = this.width || 0;
  2094. hash = (hash * 397) ^ (this.height || 0);
  2095. return hash;
  2096. };
  2097. /**
  2098. * Updates the current size from the passed one.
  2099. * Returns the updated Size.
  2100. */
  2101. Size.prototype.copyFrom = function (src) {
  2102. this.width = src.width;
  2103. this.height = src.height;
  2104. };
  2105. /**
  2106. * Updates in place the current Size from the passed floats.
  2107. * Returns the updated Size.
  2108. */
  2109. Size.prototype.copyFromFloats = function (width, height) {
  2110. this.width = width;
  2111. this.height = height;
  2112. return this;
  2113. };
  2114. /**
  2115. * Updates in place the current Size from the passed floats.
  2116. * Returns the updated Size.
  2117. */
  2118. Size.prototype.set = function (width, height) {
  2119. return this.copyFromFloats(width, height);
  2120. };
  2121. /**
  2122. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2123. */
  2124. Size.prototype.multiplyByFloats = function (w, h) {
  2125. return new Size(this.width * w, this.height * h);
  2126. };
  2127. /**
  2128. * Returns a new Size copied from the passed one.
  2129. */
  2130. Size.prototype.clone = function () {
  2131. return new Size(this.width, this.height);
  2132. };
  2133. /**
  2134. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2135. */
  2136. Size.prototype.equals = function (other) {
  2137. if (!other) {
  2138. return false;
  2139. }
  2140. return (this.width === other.width) && (this.height === other.height);
  2141. };
  2142. Object.defineProperty(Size.prototype, "surface", {
  2143. /**
  2144. * Returns the surface of the Size : width * height (float).
  2145. */
  2146. get: function () {
  2147. return this.width * this.height;
  2148. },
  2149. enumerable: true,
  2150. configurable: true
  2151. });
  2152. /**
  2153. * Returns a new Size set to (0.0, 0.0)
  2154. */
  2155. Size.Zero = function () {
  2156. return new Size(0.0, 0.0);
  2157. };
  2158. /**
  2159. * Returns a new Size set as the addition result of the current Size and the passed one.
  2160. */
  2161. Size.prototype.add = function (otherSize) {
  2162. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2163. return r;
  2164. };
  2165. /**
  2166. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2167. */
  2168. Size.prototype.subtract = function (otherSize) {
  2169. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2170. return r;
  2171. };
  2172. /**
  2173. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2174. */
  2175. Size.Lerp = function (start, end, amount) {
  2176. var w = start.width + ((end.width - start.width) * amount);
  2177. var h = start.height + ((end.height - start.height) * amount);
  2178. return new Size(w, h);
  2179. };
  2180. return Size;
  2181. }());
  2182. BABYLON.Size = Size;
  2183. var Quaternion = (function () {
  2184. /**
  2185. * Creates a new Quaternion from the passed floats.
  2186. */
  2187. function Quaternion(x, y, z, w) {
  2188. if (x === void 0) { x = 0.0; }
  2189. if (y === void 0) { y = 0.0; }
  2190. if (z === void 0) { z = 0.0; }
  2191. if (w === void 0) { w = 1.0; }
  2192. this.x = x;
  2193. this.y = y;
  2194. this.z = z;
  2195. this.w = w;
  2196. }
  2197. /**
  2198. * Returns a string with the Quaternion coordinates.
  2199. */
  2200. Quaternion.prototype.toString = function () {
  2201. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2202. };
  2203. /**
  2204. * Returns the string "Quaternion".
  2205. */
  2206. Quaternion.prototype.getClassName = function () {
  2207. return "Quaternion";
  2208. };
  2209. /**
  2210. * Returns the Quaternion hash code.
  2211. */
  2212. Quaternion.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. hash = (hash * 397) ^ (this.z || 0);
  2216. hash = (hash * 397) ^ (this.w || 0);
  2217. return hash;
  2218. };
  2219. /**
  2220. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2221. */
  2222. Quaternion.prototype.asArray = function () {
  2223. return [this.x, this.y, this.z, this.w];
  2224. };
  2225. /**
  2226. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2227. */
  2228. Quaternion.prototype.equals = function (otherQuaternion) {
  2229. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2230. };
  2231. /**
  2232. * Returns a new Quaternion copied from the current one.
  2233. */
  2234. Quaternion.prototype.clone = function () {
  2235. return new Quaternion(this.x, this.y, this.z, this.w);
  2236. };
  2237. /**
  2238. * Updates the current Quaternion from the passed one coordinates.
  2239. * Returns the updated Quaterion.
  2240. */
  2241. Quaternion.prototype.copyFrom = function (other) {
  2242. this.x = other.x;
  2243. this.y = other.y;
  2244. this.z = other.z;
  2245. this.w = other.w;
  2246. return this;
  2247. };
  2248. /**
  2249. * Updates the current Quaternion from the passed float coordinates.
  2250. * Returns the updated Quaterion.
  2251. */
  2252. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2253. this.x = x;
  2254. this.y = y;
  2255. this.z = z;
  2256. this.w = w;
  2257. return this;
  2258. };
  2259. /**
  2260. * Updates the current Quaternion from the passed float coordinates.
  2261. * Returns the updated Quaterion.
  2262. */
  2263. Quaternion.prototype.set = function (x, y, z, w) {
  2264. return this.copyFromFloats(x, y, z, w);
  2265. };
  2266. /**
  2267. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2268. */
  2269. Quaternion.prototype.add = function (other) {
  2270. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2271. };
  2272. /**
  2273. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2274. */
  2275. Quaternion.prototype.subtract = function (other) {
  2276. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2277. };
  2278. /**
  2279. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2280. */
  2281. Quaternion.prototype.scale = function (value) {
  2282. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2283. };
  2284. /**
  2285. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2286. */
  2287. Quaternion.prototype.multiply = function (q1) {
  2288. var result = new Quaternion(0, 0, 0, 1.0);
  2289. this.multiplyToRef(q1, result);
  2290. return result;
  2291. };
  2292. /**
  2293. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2294. * Returns the current Quaternion.
  2295. */
  2296. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2297. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2298. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2299. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2300. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2301. result.copyFromFloats(x, y, z, w);
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2306. * Returns the updated Quaternion.
  2307. */
  2308. Quaternion.prototype.multiplyInPlace = function (q1) {
  2309. this.multiplyToRef(q1, this);
  2310. return this;
  2311. };
  2312. /**
  2313. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2314. * Returns the current Quaternion.
  2315. */
  2316. Quaternion.prototype.conjugateToRef = function (ref) {
  2317. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2318. return this;
  2319. };
  2320. /**
  2321. * Conjugates in place the current Quaternion.
  2322. * Returns the updated Quaternion.
  2323. */
  2324. Quaternion.prototype.conjugateInPlace = function () {
  2325. this.x *= -1;
  2326. this.y *= -1;
  2327. this.z *= -1;
  2328. return this;
  2329. };
  2330. /**
  2331. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2332. */
  2333. Quaternion.prototype.conjugate = function () {
  2334. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2335. return result;
  2336. };
  2337. /**
  2338. * Returns the Quaternion length (float).
  2339. */
  2340. Quaternion.prototype.length = function () {
  2341. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2342. };
  2343. /**
  2344. * Normalize in place the current Quaternion.
  2345. * Returns the updated Quaternion.
  2346. */
  2347. Quaternion.prototype.normalize = function () {
  2348. var length = 1.0 / this.length();
  2349. this.x *= length;
  2350. this.y *= length;
  2351. this.z *= length;
  2352. this.w *= length;
  2353. return this;
  2354. };
  2355. /**
  2356. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2357. */
  2358. Quaternion.prototype.toEulerAngles = function (order) {
  2359. if (order === void 0) { order = "YZX"; }
  2360. var result = Vector3.Zero();
  2361. this.toEulerAnglesToRef(result, order);
  2362. return result;
  2363. };
  2364. /**
  2365. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2366. * Returns the current Quaternion.
  2367. */
  2368. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2369. if (order === void 0) { order = "YZX"; }
  2370. var qz = this.z;
  2371. var qx = this.x;
  2372. var qy = this.y;
  2373. var qw = this.w;
  2374. var sqw = qw * qw;
  2375. var sqz = qz * qz;
  2376. var sqx = qx * qx;
  2377. var sqy = qy * qy;
  2378. var zAxisY = qy * qz - qx * qw;
  2379. var limit = .4999999;
  2380. if (zAxisY < -limit) {
  2381. result.y = 2 * Math.atan2(qy, qw);
  2382. result.x = Math.PI / 2;
  2383. result.z = 0;
  2384. }
  2385. else if (zAxisY > limit) {
  2386. result.y = 2 * Math.atan2(qy, qw);
  2387. result.x = -Math.PI / 2;
  2388. result.z = 0;
  2389. }
  2390. else {
  2391. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2392. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2393. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2394. }
  2395. return this;
  2396. };
  2397. /**
  2398. * Updates the passed rotation matrix with the current Quaternion values.
  2399. * Returns the current Quaternion.
  2400. */
  2401. Quaternion.prototype.toRotationMatrix = function (result) {
  2402. var xx = this.x * this.x;
  2403. var yy = this.y * this.y;
  2404. var zz = this.z * this.z;
  2405. var xy = this.x * this.y;
  2406. var zw = this.z * this.w;
  2407. var zx = this.z * this.x;
  2408. var yw = this.y * this.w;
  2409. var yz = this.y * this.z;
  2410. var xw = this.x * this.w;
  2411. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2412. result.m[1] = 2.0 * (xy + zw);
  2413. result.m[2] = 2.0 * (zx - yw);
  2414. result.m[3] = 0;
  2415. result.m[4] = 2.0 * (xy - zw);
  2416. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2417. result.m[6] = 2.0 * (yz + xw);
  2418. result.m[7] = 0;
  2419. result.m[8] = 2.0 * (zx + yw);
  2420. result.m[9] = 2.0 * (yz - xw);
  2421. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2422. result.m[11] = 0;
  2423. result.m[12] = 0;
  2424. result.m[13] = 0;
  2425. result.m[14] = 0;
  2426. result.m[15] = 1.0;
  2427. return this;
  2428. };
  2429. /**
  2430. * Updates the current Quaternion from the passed rotation matrix values.
  2431. * Returns the updated Quaternion.
  2432. */
  2433. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2434. Quaternion.FromRotationMatrixToRef(matrix, this);
  2435. return this;
  2436. };
  2437. // Statics
  2438. /**
  2439. * Returns a new Quaternion set from the passed rotation matrix values.
  2440. */
  2441. Quaternion.FromRotationMatrix = function (matrix) {
  2442. var result = new Quaternion();
  2443. Quaternion.FromRotationMatrixToRef(matrix, result);
  2444. return result;
  2445. };
  2446. /**
  2447. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2448. */
  2449. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2450. var data = matrix.m;
  2451. var m11 = data[0], m12 = data[4], m13 = data[8];
  2452. var m21 = data[1], m22 = data[5], m23 = data[9];
  2453. var m31 = data[2], m32 = data[6], m33 = data[10];
  2454. var trace = m11 + m22 + m33;
  2455. var s;
  2456. if (trace > 0) {
  2457. s = 0.5 / Math.sqrt(trace + 1.0);
  2458. result.w = 0.25 / s;
  2459. result.x = (m32 - m23) * s;
  2460. result.y = (m13 - m31) * s;
  2461. result.z = (m21 - m12) * s;
  2462. }
  2463. else if (m11 > m22 && m11 > m33) {
  2464. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2465. result.w = (m32 - m23) / s;
  2466. result.x = 0.25 * s;
  2467. result.y = (m12 + m21) / s;
  2468. result.z = (m13 + m31) / s;
  2469. }
  2470. else if (m22 > m33) {
  2471. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2472. result.w = (m13 - m31) / s;
  2473. result.x = (m12 + m21) / s;
  2474. result.y = 0.25 * s;
  2475. result.z = (m23 + m32) / s;
  2476. }
  2477. else {
  2478. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2479. result.w = (m21 - m12) / s;
  2480. result.x = (m13 + m31) / s;
  2481. result.y = (m23 + m32) / s;
  2482. result.z = 0.25 * s;
  2483. }
  2484. };
  2485. /**
  2486. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2487. */
  2488. Quaternion.Zero = function () {
  2489. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2490. };
  2491. /**
  2492. * Returns a new Quaternion as the inverted current Quaternion.
  2493. */
  2494. Quaternion.Inverse = function (q) {
  2495. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2496. };
  2497. /**
  2498. * Returns the identity Quaternion.
  2499. */
  2500. Quaternion.Identity = function () {
  2501. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2502. };
  2503. Quaternion.IsIdentity = function (quaternion) {
  2504. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2505. };
  2506. /**
  2507. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2508. */
  2509. Quaternion.RotationAxis = function (axis, angle) {
  2510. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2511. };
  2512. /**
  2513. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2514. */
  2515. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2516. var sin = Math.sin(angle / 2);
  2517. axis.normalize();
  2518. result.w = Math.cos(angle / 2);
  2519. result.x = axis.x * sin;
  2520. result.y = axis.y * sin;
  2521. result.z = axis.z * sin;
  2522. return result;
  2523. };
  2524. /**
  2525. * Retuns a new Quaternion set from the starting index of the passed array.
  2526. */
  2527. Quaternion.FromArray = function (array, offset) {
  2528. if (!offset) {
  2529. offset = 0;
  2530. }
  2531. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2532. };
  2533. /**
  2534. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2535. */
  2536. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2537. var q = new Quaternion();
  2538. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2539. return q;
  2540. };
  2541. /**
  2542. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2543. */
  2544. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2545. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2546. var halfRoll = roll * 0.5;
  2547. var halfPitch = pitch * 0.5;
  2548. var halfYaw = yaw * 0.5;
  2549. var sinRoll = Math.sin(halfRoll);
  2550. var cosRoll = Math.cos(halfRoll);
  2551. var sinPitch = Math.sin(halfPitch);
  2552. var cosPitch = Math.cos(halfPitch);
  2553. var sinYaw = Math.sin(halfYaw);
  2554. var cosYaw = Math.cos(halfYaw);
  2555. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2556. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2557. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2558. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2559. };
  2560. /**
  2561. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2562. */
  2563. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2564. var result = new Quaternion();
  2565. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2566. return result;
  2567. };
  2568. /**
  2569. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2570. */
  2571. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2572. // Produces a quaternion from Euler angles in the z-x-z orientation
  2573. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2574. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2575. var halfBeta = beta * 0.5;
  2576. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2577. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2578. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2579. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2580. };
  2581. /**
  2582. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2583. * cf to Vector3.RotationFromAxis() documentation.
  2584. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2585. */
  2586. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2587. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2588. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2589. return quat;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2593. * cf to Vector3.RotationFromAxis() documentation.
  2594. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2595. */
  2596. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2597. var rotMat = MathTmp.Matrix[0];
  2598. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2599. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2600. };
  2601. Quaternion.Slerp = function (left, right, amount) {
  2602. var result = Quaternion.Identity();
  2603. Quaternion.SlerpToRef(left, right, amount, result);
  2604. return result;
  2605. };
  2606. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2607. var num2;
  2608. var num3;
  2609. var num = amount;
  2610. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2611. var flag = false;
  2612. if (num4 < 0) {
  2613. flag = true;
  2614. num4 = -num4;
  2615. }
  2616. if (num4 > 0.999999) {
  2617. num3 = 1 - num;
  2618. num2 = flag ? -num : num;
  2619. }
  2620. else {
  2621. var num5 = Math.acos(num4);
  2622. var num6 = (1.0 / Math.sin(num5));
  2623. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2624. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2625. }
  2626. result.x = (num3 * left.x) + (num2 * right.x);
  2627. result.y = (num3 * left.y) + (num2 * right.y);
  2628. result.z = (num3 * left.z) + (num2 * right.z);
  2629. result.w = (num3 * left.w) + (num2 * right.w);
  2630. };
  2631. return Quaternion;
  2632. }());
  2633. BABYLON.Quaternion = Quaternion;
  2634. var Matrix = (function () {
  2635. function Matrix() {
  2636. this.m = new Float32Array(16);
  2637. }
  2638. // Properties
  2639. /**
  2640. * Boolean : True is the matrix is the identity matrix
  2641. */
  2642. Matrix.prototype.isIdentity = function () {
  2643. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2644. return false;
  2645. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2646. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2647. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2648. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2649. return false;
  2650. return true;
  2651. };
  2652. /**
  2653. * Returns the matrix determinant (float).
  2654. */
  2655. Matrix.prototype.determinant = function () {
  2656. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2657. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2658. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2659. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2660. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2661. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2662. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2663. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2664. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2665. };
  2666. // Methods
  2667. /**
  2668. * Returns the matrix underlying array.
  2669. */
  2670. Matrix.prototype.toArray = function () {
  2671. return this.m;
  2672. };
  2673. /**
  2674. * Returns the matrix underlying array.
  2675. */
  2676. Matrix.prototype.asArray = function () {
  2677. return this.toArray();
  2678. };
  2679. /**
  2680. * Inverts in place the Matrix.
  2681. * Returns the Matrix inverted.
  2682. */
  2683. Matrix.prototype.invert = function () {
  2684. this.invertToRef(this);
  2685. return this;
  2686. };
  2687. /**
  2688. * Sets all the matrix elements to zero.
  2689. * Returns the Matrix.
  2690. */
  2691. Matrix.prototype.reset = function () {
  2692. for (var index = 0; index < 16; index++) {
  2693. this.m[index] = 0.0;
  2694. }
  2695. return this;
  2696. };
  2697. /**
  2698. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2699. */
  2700. Matrix.prototype.add = function (other) {
  2701. var result = new Matrix();
  2702. this.addToRef(other, result);
  2703. return result;
  2704. };
  2705. /**
  2706. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2707. * Returns the Matrix.
  2708. */
  2709. Matrix.prototype.addToRef = function (other, result) {
  2710. for (var index = 0; index < 16; index++) {
  2711. result.m[index] = this.m[index] + other.m[index];
  2712. }
  2713. return this;
  2714. };
  2715. /**
  2716. * Adds in place the passed matrix to the current Matrix.
  2717. * Returns the updated Matrix.
  2718. */
  2719. Matrix.prototype.addToSelf = function (other) {
  2720. for (var index = 0; index < 16; index++) {
  2721. this.m[index] += other.m[index];
  2722. }
  2723. return this;
  2724. };
  2725. /**
  2726. * Sets the passed matrix with the current inverted Matrix.
  2727. * Returns the unmodified current Matrix.
  2728. */
  2729. Matrix.prototype.invertToRef = function (other) {
  2730. var l1 = this.m[0];
  2731. var l2 = this.m[1];
  2732. var l3 = this.m[2];
  2733. var l4 = this.m[3];
  2734. var l5 = this.m[4];
  2735. var l6 = this.m[5];
  2736. var l7 = this.m[6];
  2737. var l8 = this.m[7];
  2738. var l9 = this.m[8];
  2739. var l10 = this.m[9];
  2740. var l11 = this.m[10];
  2741. var l12 = this.m[11];
  2742. var l13 = this.m[12];
  2743. var l14 = this.m[13];
  2744. var l15 = this.m[14];
  2745. var l16 = this.m[15];
  2746. var l17 = (l11 * l16) - (l12 * l15);
  2747. var l18 = (l10 * l16) - (l12 * l14);
  2748. var l19 = (l10 * l15) - (l11 * l14);
  2749. var l20 = (l9 * l16) - (l12 * l13);
  2750. var l21 = (l9 * l15) - (l11 * l13);
  2751. var l22 = (l9 * l14) - (l10 * l13);
  2752. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2753. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2754. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2755. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2756. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2757. var l28 = (l7 * l16) - (l8 * l15);
  2758. var l29 = (l6 * l16) - (l8 * l14);
  2759. var l30 = (l6 * l15) - (l7 * l14);
  2760. var l31 = (l5 * l16) - (l8 * l13);
  2761. var l32 = (l5 * l15) - (l7 * l13);
  2762. var l33 = (l5 * l14) - (l6 * l13);
  2763. var l34 = (l7 * l12) - (l8 * l11);
  2764. var l35 = (l6 * l12) - (l8 * l10);
  2765. var l36 = (l6 * l11) - (l7 * l10);
  2766. var l37 = (l5 * l12) - (l8 * l9);
  2767. var l38 = (l5 * l11) - (l7 * l9);
  2768. var l39 = (l5 * l10) - (l6 * l9);
  2769. other.m[0] = l23 * l27;
  2770. other.m[4] = l24 * l27;
  2771. other.m[8] = l25 * l27;
  2772. other.m[12] = l26 * l27;
  2773. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2774. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2775. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2776. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2777. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2778. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2779. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2780. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2781. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2782. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2783. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2784. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2785. return this;
  2786. };
  2787. /**
  2788. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2789. * Returns the updated Matrix.
  2790. */
  2791. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2792. this.m[12] = x;
  2793. this.m[13] = y;
  2794. this.m[14] = z;
  2795. return this;
  2796. };
  2797. /**
  2798. * Inserts the translation vector in the current Matrix.
  2799. * Returns the updated Matrix.
  2800. */
  2801. Matrix.prototype.setTranslation = function (vector3) {
  2802. this.m[12] = vector3.x;
  2803. this.m[13] = vector3.y;
  2804. this.m[14] = vector3.z;
  2805. return this;
  2806. };
  2807. /**
  2808. * Returns a new Vector3 as the extracted translation from the Matrix.
  2809. */
  2810. Matrix.prototype.getTranslation = function () {
  2811. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2812. };
  2813. /**
  2814. * Fill a Vector3 with the extracted translation from the Matrix.
  2815. */
  2816. Matrix.prototype.getTranslationToRef = function (result) {
  2817. result.x = this.m[12];
  2818. result.y = this.m[13];
  2819. result.z = this.m[14];
  2820. return this;
  2821. };
  2822. /**
  2823. * Remove rotation and scaling part from the Matrix.
  2824. * Returns the updated Matrix.
  2825. */
  2826. Matrix.prototype.removeRotationAndScaling = function () {
  2827. this.setRowFromFloats(0, 1, 0, 0, 0);
  2828. this.setRowFromFloats(1, 0, 1, 0, 0);
  2829. this.setRowFromFloats(2, 0, 0, 1, 0);
  2830. return this;
  2831. };
  2832. /**
  2833. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2834. */
  2835. Matrix.prototype.multiply = function (other) {
  2836. var result = new Matrix();
  2837. this.multiplyToRef(other, result);
  2838. return result;
  2839. };
  2840. /**
  2841. * Updates the current Matrix from the passed one values.
  2842. * Returns the updated Matrix.
  2843. */
  2844. Matrix.prototype.copyFrom = function (other) {
  2845. for (var index = 0; index < 16; index++) {
  2846. this.m[index] = other.m[index];
  2847. }
  2848. return this;
  2849. };
  2850. /**
  2851. * Populates the passed array from the starting index with the Matrix values.
  2852. * Returns the Matrix.
  2853. */
  2854. Matrix.prototype.copyToArray = function (array, offset) {
  2855. if (offset === void 0) { offset = 0; }
  2856. for (var index = 0; index < 16; index++) {
  2857. array[offset + index] = this.m[index];
  2858. }
  2859. return this;
  2860. };
  2861. /**
  2862. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2863. */
  2864. Matrix.prototype.multiplyToRef = function (other, result) {
  2865. this.multiplyToArray(other, result.m, 0);
  2866. return this;
  2867. };
  2868. /**
  2869. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2870. */
  2871. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2872. var tm0 = this.m[0];
  2873. var tm1 = this.m[1];
  2874. var tm2 = this.m[2];
  2875. var tm3 = this.m[3];
  2876. var tm4 = this.m[4];
  2877. var tm5 = this.m[5];
  2878. var tm6 = this.m[6];
  2879. var tm7 = this.m[7];
  2880. var tm8 = this.m[8];
  2881. var tm9 = this.m[9];
  2882. var tm10 = this.m[10];
  2883. var tm11 = this.m[11];
  2884. var tm12 = this.m[12];
  2885. var tm13 = this.m[13];
  2886. var tm14 = this.m[14];
  2887. var tm15 = this.m[15];
  2888. var om0 = other.m[0];
  2889. var om1 = other.m[1];
  2890. var om2 = other.m[2];
  2891. var om3 = other.m[3];
  2892. var om4 = other.m[4];
  2893. var om5 = other.m[5];
  2894. var om6 = other.m[6];
  2895. var om7 = other.m[7];
  2896. var om8 = other.m[8];
  2897. var om9 = other.m[9];
  2898. var om10 = other.m[10];
  2899. var om11 = other.m[11];
  2900. var om12 = other.m[12];
  2901. var om13 = other.m[13];
  2902. var om14 = other.m[14];
  2903. var om15 = other.m[15];
  2904. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2905. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2906. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2907. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2908. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2909. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2910. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2911. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2912. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2913. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2914. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2915. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2916. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2917. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2918. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2919. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2920. return this;
  2921. };
  2922. /**
  2923. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2924. */
  2925. Matrix.prototype.equals = function (value) {
  2926. return value &&
  2927. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2928. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2929. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2930. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2931. };
  2932. /**
  2933. * Returns a new Matrix from the current Matrix.
  2934. */
  2935. Matrix.prototype.clone = function () {
  2936. 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]);
  2937. };
  2938. /**
  2939. * Returns the string "Matrix"
  2940. */
  2941. Matrix.prototype.getClassName = function () {
  2942. return "Matrix";
  2943. };
  2944. /**
  2945. * Returns the Matrix hash code.
  2946. */
  2947. Matrix.prototype.getHashCode = function () {
  2948. var hash = this.m[0] || 0;
  2949. for (var i = 1; i < 16; i++) {
  2950. hash = (hash * 397) ^ (this.m[i] || 0);
  2951. }
  2952. return hash;
  2953. };
  2954. /**
  2955. * Decomposes the current Matrix into :
  2956. * - a scale vector3 passed as a reference to update,
  2957. * - a rotation quaternion passed as a reference to update,
  2958. * - a translation vector3 passed as a reference to update.
  2959. * Returns the boolean `true`.
  2960. */
  2961. Matrix.prototype.decompose = function (scale, rotation, translation) {
  2962. translation.x = this.m[12];
  2963. translation.y = this.m[13];
  2964. translation.z = this.m[14];
  2965. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  2966. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  2967. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  2968. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  2969. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  2970. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  2971. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  2972. rotation.x = 0;
  2973. rotation.y = 0;
  2974. rotation.z = 0;
  2975. rotation.w = 1;
  2976. return false;
  2977. }
  2978. 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]);
  2979. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  2980. return true;
  2981. };
  2982. /**
  2983. * Returns a new Matrix as the extracted rotation matrix from the current one.
  2984. */
  2985. Matrix.prototype.getRotationMatrix = function () {
  2986. var result = Matrix.Identity();
  2987. this.getRotationMatrixToRef(result);
  2988. return result;
  2989. };
  2990. /**
  2991. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  2992. * Returns the current Matrix.
  2993. */
  2994. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2995. var m = this.m;
  2996. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2997. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2998. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2999. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3000. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3001. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3002. 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);
  3003. return this;
  3004. };
  3005. // Statics
  3006. /**
  3007. * Returns a new Matrix set from the starting index of the passed array.
  3008. */
  3009. Matrix.FromArray = function (array, offset) {
  3010. var result = new Matrix();
  3011. if (!offset) {
  3012. offset = 0;
  3013. }
  3014. Matrix.FromArrayToRef(array, offset, result);
  3015. return result;
  3016. };
  3017. /**
  3018. * Sets the passed "result" matrix from the starting index of the passed array.
  3019. */
  3020. Matrix.FromArrayToRef = function (array, offset, result) {
  3021. for (var index = 0; index < 16; index++) {
  3022. result.m[index] = array[index + offset];
  3023. }
  3024. };
  3025. /**
  3026. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3027. */
  3028. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3029. for (var index = 0; index < 16; index++) {
  3030. result.m[index] = array[index + offset] * scale;
  3031. }
  3032. };
  3033. /**
  3034. * Sets the passed matrix "result" with the 16 passed floats.
  3035. */
  3036. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3037. result.m[0] = initialM11;
  3038. result.m[1] = initialM12;
  3039. result.m[2] = initialM13;
  3040. result.m[3] = initialM14;
  3041. result.m[4] = initialM21;
  3042. result.m[5] = initialM22;
  3043. result.m[6] = initialM23;
  3044. result.m[7] = initialM24;
  3045. result.m[8] = initialM31;
  3046. result.m[9] = initialM32;
  3047. result.m[10] = initialM33;
  3048. result.m[11] = initialM34;
  3049. result.m[12] = initialM41;
  3050. result.m[13] = initialM42;
  3051. result.m[14] = initialM43;
  3052. result.m[15] = initialM44;
  3053. };
  3054. /**
  3055. * Returns the index-th row of the current matrix as a new Vector4.
  3056. */
  3057. Matrix.prototype.getRow = function (index) {
  3058. if (index < 0 || index > 3) {
  3059. return null;
  3060. }
  3061. var i = index * 4;
  3062. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3063. };
  3064. /**
  3065. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.setRow = function (index, row) {
  3069. if (index < 0 || index > 3) {
  3070. return this;
  3071. }
  3072. var i = index * 4;
  3073. this.m[i + 0] = row.x;
  3074. this.m[i + 1] = row.y;
  3075. this.m[i + 2] = row.z;
  3076. this.m[i + 3] = row.w;
  3077. return this;
  3078. };
  3079. /**
  3080. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3081. * Returns the updated Matrix.
  3082. */
  3083. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3084. if (index < 0 || index > 3) {
  3085. return this;
  3086. }
  3087. var i = index * 4;
  3088. this.m[i + 0] = x;
  3089. this.m[i + 1] = y;
  3090. this.m[i + 2] = z;
  3091. this.m[i + 3] = w;
  3092. return this;
  3093. };
  3094. /**
  3095. * Returns a new Matrix set from the 16 passed floats.
  3096. */
  3097. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3098. var result = new Matrix();
  3099. result.m[0] = initialM11;
  3100. result.m[1] = initialM12;
  3101. result.m[2] = initialM13;
  3102. result.m[3] = initialM14;
  3103. result.m[4] = initialM21;
  3104. result.m[5] = initialM22;
  3105. result.m[6] = initialM23;
  3106. result.m[7] = initialM24;
  3107. result.m[8] = initialM31;
  3108. result.m[9] = initialM32;
  3109. result.m[10] = initialM33;
  3110. result.m[11] = initialM34;
  3111. result.m[12] = initialM41;
  3112. result.m[13] = initialM42;
  3113. result.m[14] = initialM43;
  3114. result.m[15] = initialM44;
  3115. return result;
  3116. };
  3117. /**
  3118. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3119. */
  3120. Matrix.Compose = function (scale, rotation, translation) {
  3121. var result = Matrix.Identity();
  3122. Matrix.ComposeToRef(scale, rotation, translation, result);
  3123. return result;
  3124. };
  3125. /**
  3126. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3127. */
  3128. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3129. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3130. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3131. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3132. result.setTranslation(translation);
  3133. };
  3134. /**
  3135. * Returns a new indentity Matrix.
  3136. */
  3137. Matrix.Identity = function () {
  3138. 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);
  3139. };
  3140. /**
  3141. * Sets the passed "result" as an identity matrix.
  3142. */
  3143. Matrix.IdentityToRef = function (result) {
  3144. 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);
  3145. };
  3146. /**
  3147. * Returns a new zero Matrix.
  3148. */
  3149. Matrix.Zero = function () {
  3150. 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);
  3151. };
  3152. /**
  3153. * Returns a new rotation matrix for "angle" radians around the X axis.
  3154. */
  3155. Matrix.RotationX = function (angle) {
  3156. var result = new Matrix();
  3157. Matrix.RotationXToRef(angle, result);
  3158. return result;
  3159. };
  3160. /**
  3161. * Returns a new Matrix as the passed inverted one.
  3162. */
  3163. Matrix.Invert = function (source) {
  3164. var result = new Matrix();
  3165. source.invertToRef(result);
  3166. return result;
  3167. };
  3168. /**
  3169. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3170. */
  3171. Matrix.RotationXToRef = function (angle, result) {
  3172. var s = Math.sin(angle);
  3173. var c = Math.cos(angle);
  3174. result.m[0] = 1.0;
  3175. result.m[15] = 1.0;
  3176. result.m[5] = c;
  3177. result.m[10] = c;
  3178. result.m[9] = -s;
  3179. result.m[6] = s;
  3180. result.m[1] = 0.0;
  3181. result.m[2] = 0.0;
  3182. result.m[3] = 0.0;
  3183. result.m[4] = 0.0;
  3184. result.m[7] = 0.0;
  3185. result.m[8] = 0.0;
  3186. result.m[11] = 0.0;
  3187. result.m[12] = 0.0;
  3188. result.m[13] = 0.0;
  3189. result.m[14] = 0.0;
  3190. };
  3191. /**
  3192. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3193. */
  3194. Matrix.RotationY = function (angle) {
  3195. var result = new Matrix();
  3196. Matrix.RotationYToRef(angle, result);
  3197. return result;
  3198. };
  3199. /**
  3200. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3201. */
  3202. Matrix.RotationYToRef = function (angle, result) {
  3203. var s = Math.sin(angle);
  3204. var c = Math.cos(angle);
  3205. result.m[5] = 1.0;
  3206. result.m[15] = 1.0;
  3207. result.m[0] = c;
  3208. result.m[2] = -s;
  3209. result.m[8] = s;
  3210. result.m[10] = c;
  3211. result.m[1] = 0.0;
  3212. result.m[3] = 0.0;
  3213. result.m[4] = 0.0;
  3214. result.m[6] = 0.0;
  3215. result.m[7] = 0.0;
  3216. result.m[9] = 0.0;
  3217. result.m[11] = 0.0;
  3218. result.m[12] = 0.0;
  3219. result.m[13] = 0.0;
  3220. result.m[14] = 0.0;
  3221. };
  3222. /**
  3223. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3224. */
  3225. Matrix.RotationZ = function (angle) {
  3226. var result = new Matrix();
  3227. Matrix.RotationZToRef(angle, result);
  3228. return result;
  3229. };
  3230. /**
  3231. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3232. */
  3233. Matrix.RotationZToRef = function (angle, result) {
  3234. var s = Math.sin(angle);
  3235. var c = Math.cos(angle);
  3236. result.m[10] = 1.0;
  3237. result.m[15] = 1.0;
  3238. result.m[0] = c;
  3239. result.m[1] = s;
  3240. result.m[4] = -s;
  3241. result.m[5] = c;
  3242. result.m[2] = 0.0;
  3243. result.m[3] = 0.0;
  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[11] = 0.0;
  3249. result.m[12] = 0.0;
  3250. result.m[13] = 0.0;
  3251. result.m[14] = 0.0;
  3252. };
  3253. /**
  3254. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3255. */
  3256. Matrix.RotationAxis = function (axis, angle) {
  3257. var result = Matrix.Zero();
  3258. Matrix.RotationAxisToRef(axis, angle, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3263. */
  3264. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3265. var s = Math.sin(-angle);
  3266. var c = Math.cos(-angle);
  3267. var c1 = 1 - c;
  3268. axis.normalize();
  3269. result.m[0] = (axis.x * axis.x) * c1 + c;
  3270. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3271. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3272. result.m[3] = 0.0;
  3273. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3274. result.m[5] = (axis.y * axis.y) * c1 + c;
  3275. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3276. result.m[7] = 0.0;
  3277. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3278. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3279. result.m[10] = (axis.z * axis.z) * c1 + c;
  3280. result.m[11] = 0.0;
  3281. result.m[15] = 1.0;
  3282. };
  3283. /**
  3284. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3285. */
  3286. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3287. var result = new Matrix();
  3288. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3289. return result;
  3290. };
  3291. /**
  3292. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3293. */
  3294. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3295. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3296. this._tempQuaternion.toRotationMatrix(result);
  3297. };
  3298. /**
  3299. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3300. */
  3301. Matrix.Scaling = function (x, y, z) {
  3302. var result = Matrix.Zero();
  3303. Matrix.ScalingToRef(x, y, z, result);
  3304. return result;
  3305. };
  3306. /**
  3307. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3308. */
  3309. Matrix.ScalingToRef = function (x, y, z, result) {
  3310. result.m[0] = x;
  3311. result.m[1] = 0.0;
  3312. result.m[2] = 0.0;
  3313. result.m[3] = 0.0;
  3314. result.m[4] = 0.0;
  3315. result.m[5] = y;
  3316. result.m[6] = 0.0;
  3317. result.m[7] = 0.0;
  3318. result.m[8] = 0.0;
  3319. result.m[9] = 0.0;
  3320. result.m[10] = z;
  3321. result.m[11] = 0.0;
  3322. result.m[12] = 0.0;
  3323. result.m[13] = 0.0;
  3324. result.m[14] = 0.0;
  3325. result.m[15] = 1.0;
  3326. };
  3327. /**
  3328. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3329. */
  3330. Matrix.Translation = function (x, y, z) {
  3331. var result = Matrix.Identity();
  3332. Matrix.TranslationToRef(x, y, z, result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3337. */
  3338. Matrix.TranslationToRef = function (x, y, z, result) {
  3339. 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);
  3340. };
  3341. /**
  3342. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3343. */
  3344. Matrix.Lerp = function (startValue, endValue, gradient) {
  3345. var result = Matrix.Zero();
  3346. for (var index = 0; index < 16; index++) {
  3347. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3348. }
  3349. return result;
  3350. };
  3351. /**
  3352. * Returns a new Matrix whose values are computed by :
  3353. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3354. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3355. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3356. */
  3357. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3358. var startScale = new Vector3(0, 0, 0);
  3359. var startRotation = new Quaternion();
  3360. var startTranslation = new Vector3(0, 0, 0);
  3361. startValue.decompose(startScale, startRotation, startTranslation);
  3362. var endScale = new Vector3(0, 0, 0);
  3363. var endRotation = new Quaternion();
  3364. var endTranslation = new Vector3(0, 0, 0);
  3365. endValue.decompose(endScale, endRotation, endTranslation);
  3366. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3367. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3368. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3369. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3370. };
  3371. /**
  3372. * 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".
  3373. * This methods works for a Left-Handed system.
  3374. */
  3375. Matrix.LookAtLH = function (eye, target, up) {
  3376. var result = Matrix.Zero();
  3377. Matrix.LookAtLHToRef(eye, target, up, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * 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".
  3382. * This methods works for a Left-Handed system.
  3383. */
  3384. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3385. // Z axis
  3386. target.subtractToRef(eye, this._zAxis);
  3387. this._zAxis.normalize();
  3388. // X axis
  3389. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3390. if (this._xAxis.lengthSquared() === 0) {
  3391. this._xAxis.x = 1.0;
  3392. }
  3393. else {
  3394. this._xAxis.normalize();
  3395. }
  3396. // Y axis
  3397. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3398. this._yAxis.normalize();
  3399. // Eye angles
  3400. var ex = -Vector3.Dot(this._xAxis, eye);
  3401. var ey = -Vector3.Dot(this._yAxis, eye);
  3402. var ez = -Vector3.Dot(this._zAxis, eye);
  3403. 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);
  3404. };
  3405. /**
  3406. * 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".
  3407. * This methods works for a Right-Handed system.
  3408. */
  3409. Matrix.LookAtRH = function (eye, target, up) {
  3410. var result = Matrix.Zero();
  3411. Matrix.LookAtRHToRef(eye, target, up, result);
  3412. return result;
  3413. };
  3414. /**
  3415. * 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".
  3416. * This methods works for a Left-Handed system.
  3417. */
  3418. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3419. // Z axis
  3420. eye.subtractToRef(target, this._zAxis);
  3421. this._zAxis.normalize();
  3422. // X axis
  3423. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3424. if (this._xAxis.lengthSquared() === 0) {
  3425. this._xAxis.x = 1.0;
  3426. }
  3427. else {
  3428. this._xAxis.normalize();
  3429. }
  3430. // Y axis
  3431. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3432. this._yAxis.normalize();
  3433. // Eye angles
  3434. var ex = -Vector3.Dot(this._xAxis, eye);
  3435. var ey = -Vector3.Dot(this._yAxis, eye);
  3436. var ez = -Vector3.Dot(this._zAxis, eye);
  3437. 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);
  3438. };
  3439. /**
  3440. * 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.
  3441. */
  3442. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3443. var matrix = Matrix.Zero();
  3444. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3445. return matrix;
  3446. };
  3447. /**
  3448. * 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.
  3449. */
  3450. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3451. var n = znear;
  3452. var f = zfar;
  3453. var a = 2.0 / width;
  3454. var b = 2.0 / height;
  3455. var c = 2.0 / (f - n);
  3456. var d = -(f + n) / (f - n);
  3457. 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);
  3458. };
  3459. /**
  3460. * 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.
  3461. */
  3462. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3463. var matrix = Matrix.Zero();
  3464. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3465. return matrix;
  3466. };
  3467. /**
  3468. * 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.
  3469. */
  3470. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3471. var n = znear;
  3472. var f = zfar;
  3473. var a = 2.0 / (right - left);
  3474. var b = 2.0 / (top - bottom);
  3475. var c = 2.0 / (f - n);
  3476. var d = -(f + n) / (f - n);
  3477. var i0 = (left + right) / (left - right);
  3478. var i1 = (top + bottom) / (bottom - top);
  3479. 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);
  3480. };
  3481. /**
  3482. * 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.
  3483. */
  3484. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3485. var matrix = Matrix.Zero();
  3486. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3487. return matrix;
  3488. };
  3489. /**
  3490. * 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.
  3491. */
  3492. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3493. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3494. result.m[10] *= -1.0;
  3495. };
  3496. /**
  3497. * 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.
  3498. */
  3499. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3500. var matrix = Matrix.Zero();
  3501. var n = znear;
  3502. var f = zfar;
  3503. var a = 2.0 * n / width;
  3504. var b = 2.0 * n / height;
  3505. var c = (f + n) / (f - n);
  3506. var d = -2.0 * f * n / (f - n);
  3507. 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);
  3508. return matrix;
  3509. };
  3510. /**
  3511. * 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.
  3512. */
  3513. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3514. var matrix = Matrix.Zero();
  3515. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3516. return matrix;
  3517. };
  3518. /**
  3519. * 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.
  3520. */
  3521. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3522. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3523. var n = znear;
  3524. var f = zfar;
  3525. var t = 1.0 / (Math.tan(fov * 0.5));
  3526. var a = isVerticalFovFixed ? (t / aspect) : t;
  3527. var b = isVerticalFovFixed ? t : (t * aspect);
  3528. var c = (f + n) / (f - n);
  3529. var d = -2.0 * f * n / (f - n);
  3530. 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);
  3531. };
  3532. /**
  3533. * 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.
  3534. */
  3535. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3536. var matrix = Matrix.Zero();
  3537. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3538. return matrix;
  3539. };
  3540. /**
  3541. * 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.
  3542. */
  3543. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3544. //alternatively this could be expressed as:
  3545. // m = PerspectiveFovLHToRef
  3546. // m[10] *= -1.0;
  3547. // m[11] *= -1.0;
  3548. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3549. var n = znear;
  3550. var f = zfar;
  3551. var t = 1.0 / (Math.tan(fov * 0.5));
  3552. var a = isVerticalFovFixed ? (t / aspect) : t;
  3553. var b = isVerticalFovFixed ? t : (t * aspect);
  3554. var c = -(f + n) / (f - n);
  3555. var d = -2 * f * n / (f - n);
  3556. 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);
  3557. };
  3558. /**
  3559. * 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.
  3560. */
  3561. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3562. if (rightHanded === void 0) { rightHanded = false; }
  3563. var rightHandedFactor = rightHanded ? -1 : 1;
  3564. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3565. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3566. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3567. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3568. var xScale = 2.0 / (leftTan + rightTan);
  3569. var yScale = 2.0 / (upTan + downTan);
  3570. result.m[0] = xScale;
  3571. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3572. result.m[5] = yScale;
  3573. result.m[6] = result.m[7] = 0.0;
  3574. result.m[8] = ((leftTan - rightTan) * xScale * 0.5) * rightHandedFactor;
  3575. result.m[9] = -((upTan - downTan) * yScale * 0.5) * rightHandedFactor;
  3576. result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3577. // result.m[10] = -zfar / (znear - zfar);
  3578. result.m[11] = 1.0 * rightHandedFactor;
  3579. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3580. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3581. // result.m[14] = (znear * zfar) / (znear - zfar);
  3582. };
  3583. /**
  3584. * Returns the final transformation matrix : world * view * projection * viewport
  3585. */
  3586. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3587. var cw = viewport.width;
  3588. var ch = viewport.height;
  3589. var cx = viewport.x;
  3590. var cy = viewport.y;
  3591. 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);
  3592. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3593. };
  3594. /**
  3595. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3596. */
  3597. Matrix.GetAsMatrix2x2 = function (matrix) {
  3598. return new Float32Array([
  3599. matrix.m[0], matrix.m[1],
  3600. matrix.m[4], matrix.m[5]
  3601. ]);
  3602. };
  3603. /**
  3604. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3605. */
  3606. Matrix.GetAsMatrix3x3 = function (matrix) {
  3607. return new Float32Array([
  3608. matrix.m[0], matrix.m[1], matrix.m[2],
  3609. matrix.m[4], matrix.m[5], matrix.m[6],
  3610. matrix.m[8], matrix.m[9], matrix.m[10]
  3611. ]);
  3612. };
  3613. /**
  3614. * Compute the transpose of the passed Matrix.
  3615. * Returns a new Matrix.
  3616. */
  3617. Matrix.Transpose = function (matrix) {
  3618. var result = new Matrix();
  3619. result.m[0] = matrix.m[0];
  3620. result.m[1] = matrix.m[4];
  3621. result.m[2] = matrix.m[8];
  3622. result.m[3] = matrix.m[12];
  3623. result.m[4] = matrix.m[1];
  3624. result.m[5] = matrix.m[5];
  3625. result.m[6] = matrix.m[9];
  3626. result.m[7] = matrix.m[13];
  3627. result.m[8] = matrix.m[2];
  3628. result.m[9] = matrix.m[6];
  3629. result.m[10] = matrix.m[10];
  3630. result.m[11] = matrix.m[14];
  3631. result.m[12] = matrix.m[3];
  3632. result.m[13] = matrix.m[7];
  3633. result.m[14] = matrix.m[11];
  3634. result.m[15] = matrix.m[15];
  3635. return result;
  3636. };
  3637. /**
  3638. * Returns a new Matrix as the reflection matrix across the passed plane.
  3639. */
  3640. Matrix.Reflection = function (plane) {
  3641. var matrix = new Matrix();
  3642. Matrix.ReflectionToRef(plane, matrix);
  3643. return matrix;
  3644. };
  3645. /**
  3646. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3647. */
  3648. Matrix.ReflectionToRef = function (plane, result) {
  3649. plane.normalize();
  3650. var x = plane.normal.x;
  3651. var y = plane.normal.y;
  3652. var z = plane.normal.z;
  3653. var temp = -2 * x;
  3654. var temp2 = -2 * y;
  3655. var temp3 = -2 * z;
  3656. result.m[0] = (temp * x) + 1;
  3657. result.m[1] = temp2 * x;
  3658. result.m[2] = temp3 * x;
  3659. result.m[3] = 0.0;
  3660. result.m[4] = temp * y;
  3661. result.m[5] = (temp2 * y) + 1;
  3662. result.m[6] = temp3 * y;
  3663. result.m[7] = 0.0;
  3664. result.m[8] = temp * z;
  3665. result.m[9] = temp2 * z;
  3666. result.m[10] = (temp3 * z) + 1;
  3667. result.m[11] = 0.0;
  3668. result.m[12] = temp * plane.d;
  3669. result.m[13] = temp2 * plane.d;
  3670. result.m[14] = temp3 * plane.d;
  3671. result.m[15] = 1.0;
  3672. };
  3673. /**
  3674. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3675. */
  3676. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  3677. mat.m[0] = xaxis.x;
  3678. mat.m[1] = xaxis.y;
  3679. mat.m[2] = xaxis.z;
  3680. mat.m[3] = 0.0;
  3681. mat.m[4] = yaxis.x;
  3682. mat.m[5] = yaxis.y;
  3683. mat.m[6] = yaxis.z;
  3684. mat.m[7] = 0.0;
  3685. mat.m[8] = zaxis.x;
  3686. mat.m[9] = zaxis.y;
  3687. mat.m[10] = zaxis.z;
  3688. mat.m[11] = 0.0;
  3689. mat.m[12] = 0.0;
  3690. mat.m[13] = 0.0;
  3691. mat.m[14] = 0.0;
  3692. mat.m[15] = 1.0;
  3693. };
  3694. /**
  3695. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3696. */
  3697. Matrix.FromQuaternionToRef = function (quat, result) {
  3698. var xx = quat.x * quat.x;
  3699. var yy = quat.y * quat.y;
  3700. var zz = quat.z * quat.z;
  3701. var xy = quat.x * quat.y;
  3702. var zw = quat.z * quat.w;
  3703. var zx = quat.z * quat.x;
  3704. var yw = quat.y * quat.w;
  3705. var yz = quat.y * quat.z;
  3706. var xw = quat.x * quat.w;
  3707. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3708. result.m[1] = 2.0 * (xy + zw);
  3709. result.m[2] = 2.0 * (zx - yw);
  3710. result.m[3] = 0.0;
  3711. result.m[4] = 2.0 * (xy - zw);
  3712. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3713. result.m[6] = 2.0 * (yz + xw);
  3714. result.m[7] = 0.0;
  3715. result.m[8] = 2.0 * (zx + yw);
  3716. result.m[9] = 2.0 * (yz - xw);
  3717. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3718. result.m[11] = 0.0;
  3719. result.m[12] = 0.0;
  3720. result.m[13] = 0.0;
  3721. result.m[14] = 0.0;
  3722. result.m[15] = 1.0;
  3723. };
  3724. return Matrix;
  3725. }());
  3726. Matrix._tempQuaternion = new Quaternion();
  3727. Matrix._xAxis = Vector3.Zero();
  3728. Matrix._yAxis = Vector3.Zero();
  3729. Matrix._zAxis = Vector3.Zero();
  3730. BABYLON.Matrix = Matrix;
  3731. var Plane = (function () {
  3732. /**
  3733. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3734. */
  3735. function Plane(a, b, c, d) {
  3736. this.normal = new Vector3(a, b, c);
  3737. this.d = d;
  3738. }
  3739. /**
  3740. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3741. */
  3742. Plane.prototype.asArray = function () {
  3743. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3744. };
  3745. // Methods
  3746. /**
  3747. * Returns a new plane copied from the current Plane.
  3748. */
  3749. Plane.prototype.clone = function () {
  3750. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3751. };
  3752. /**
  3753. * Returns the string "Plane".
  3754. */
  3755. Plane.prototype.getClassName = function () {
  3756. return "Plane";
  3757. };
  3758. /**
  3759. * Returns the Plane hash code.
  3760. */
  3761. Plane.prototype.getHashCode = function () {
  3762. var hash = this.normal.getHashCode();
  3763. hash = (hash * 397) ^ (this.d || 0);
  3764. return hash;
  3765. };
  3766. /**
  3767. * Normalize the current Plane in place.
  3768. * Returns the updated Plane.
  3769. */
  3770. Plane.prototype.normalize = function () {
  3771. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3772. var magnitude = 0.0;
  3773. if (norm !== 0) {
  3774. magnitude = 1.0 / norm;
  3775. }
  3776. this.normal.x *= magnitude;
  3777. this.normal.y *= magnitude;
  3778. this.normal.z *= magnitude;
  3779. this.d *= magnitude;
  3780. return this;
  3781. };
  3782. /**
  3783. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3784. */
  3785. Plane.prototype.transform = function (transformation) {
  3786. var transposedMatrix = Matrix.Transpose(transformation);
  3787. var x = this.normal.x;
  3788. var y = this.normal.y;
  3789. var z = this.normal.z;
  3790. var d = this.d;
  3791. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3792. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3793. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3794. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3795. return new Plane(normalX, normalY, normalZ, finalD);
  3796. };
  3797. /**
  3798. * Returns the dot product (float) of the point coordinates and the plane normal.
  3799. */
  3800. Plane.prototype.dotCoordinate = function (point) {
  3801. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3802. };
  3803. /**
  3804. * Updates the current Plane from the plane defined by the three passed points.
  3805. * Returns the updated Plane.
  3806. */
  3807. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3808. var x1 = point2.x - point1.x;
  3809. var y1 = point2.y - point1.y;
  3810. var z1 = point2.z - point1.z;
  3811. var x2 = point3.x - point1.x;
  3812. var y2 = point3.y - point1.y;
  3813. var z2 = point3.z - point1.z;
  3814. var yz = (y1 * z2) - (z1 * y2);
  3815. var xz = (z1 * x2) - (x1 * z2);
  3816. var xy = (x1 * y2) - (y1 * x2);
  3817. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3818. var invPyth;
  3819. if (pyth !== 0) {
  3820. invPyth = 1.0 / pyth;
  3821. }
  3822. else {
  3823. invPyth = 0.0;
  3824. }
  3825. this.normal.x = yz * invPyth;
  3826. this.normal.y = xz * invPyth;
  3827. this.normal.z = xy * invPyth;
  3828. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3829. return this;
  3830. };
  3831. /**
  3832. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3833. */
  3834. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3835. var dot = Vector3.Dot(this.normal, direction);
  3836. return (dot <= epsilon);
  3837. };
  3838. /**
  3839. * Returns the signed distance (float) from the passed point to the Plane.
  3840. */
  3841. Plane.prototype.signedDistanceTo = function (point) {
  3842. return Vector3.Dot(point, this.normal) + this.d;
  3843. };
  3844. // Statics
  3845. /**
  3846. * Returns a new Plane from the passed array.
  3847. */
  3848. Plane.FromArray = function (array) {
  3849. return new Plane(array[0], array[1], array[2], array[3]);
  3850. };
  3851. /**
  3852. * Returns a new Plane defined by the three passed points.
  3853. */
  3854. Plane.FromPoints = function (point1, point2, point3) {
  3855. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3856. result.copyFromPoints(point1, point2, point3);
  3857. return result;
  3858. };
  3859. /**
  3860. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3861. * Note : the vector "normal" is updated because normalized.
  3862. */
  3863. Plane.FromPositionAndNormal = function (origin, normal) {
  3864. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3865. normal.normalize();
  3866. result.normal = normal;
  3867. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3868. return result;
  3869. };
  3870. /**
  3871. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3872. */
  3873. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3874. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3875. return Vector3.Dot(point, normal) + d;
  3876. };
  3877. return Plane;
  3878. }());
  3879. BABYLON.Plane = Plane;
  3880. var Viewport = (function () {
  3881. /**
  3882. * Creates a Viewport object located at (x, y) and sized (width, height).
  3883. */
  3884. function Viewport(x, y, width, height) {
  3885. this.x = x;
  3886. this.y = y;
  3887. this.width = width;
  3888. this.height = height;
  3889. }
  3890. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3891. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3892. };
  3893. /**
  3894. * Returns a new Viewport copied from the current one.
  3895. */
  3896. Viewport.prototype.clone = function () {
  3897. return new Viewport(this.x, this.y, this.width, this.height);
  3898. };
  3899. return Viewport;
  3900. }());
  3901. BABYLON.Viewport = Viewport;
  3902. var Frustum = (function () {
  3903. function Frustum() {
  3904. }
  3905. /**
  3906. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3907. */
  3908. Frustum.GetPlanes = function (transform) {
  3909. var frustumPlanes = [];
  3910. for (var index = 0; index < 6; index++) {
  3911. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3912. }
  3913. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3914. return frustumPlanes;
  3915. };
  3916. /**
  3917. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3918. */
  3919. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3920. // Near
  3921. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3922. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3923. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3924. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3925. frustumPlanes[0].normalize();
  3926. // Far
  3927. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3928. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3929. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3930. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3931. frustumPlanes[1].normalize();
  3932. // Left
  3933. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3934. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3935. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3936. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3937. frustumPlanes[2].normalize();
  3938. // Right
  3939. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  3940. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  3941. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  3942. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  3943. frustumPlanes[3].normalize();
  3944. // Top
  3945. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  3946. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  3947. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  3948. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  3949. frustumPlanes[4].normalize();
  3950. // Bottom
  3951. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  3952. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  3953. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  3954. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  3955. frustumPlanes[5].normalize();
  3956. };
  3957. return Frustum;
  3958. }());
  3959. BABYLON.Frustum = Frustum;
  3960. var Space;
  3961. (function (Space) {
  3962. Space[Space["LOCAL"] = 0] = "LOCAL";
  3963. Space[Space["WORLD"] = 1] = "WORLD";
  3964. Space[Space["BONE"] = 2] = "BONE";
  3965. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  3966. var Axis = (function () {
  3967. function Axis() {
  3968. }
  3969. return Axis;
  3970. }());
  3971. Axis.X = new Vector3(1.0, 0.0, 0.0);
  3972. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  3973. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  3974. BABYLON.Axis = Axis;
  3975. ;
  3976. var BezierCurve = (function () {
  3977. function BezierCurve() {
  3978. }
  3979. /**
  3980. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  3981. */
  3982. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  3983. // Extract X (which is equal to time here)
  3984. var f0 = 1 - 3 * x2 + 3 * x1;
  3985. var f1 = 3 * x2 - 6 * x1;
  3986. var f2 = 3 * x1;
  3987. var refinedT = t;
  3988. for (var i = 0; i < 5; i++) {
  3989. var refinedT2 = refinedT * refinedT;
  3990. var refinedT3 = refinedT2 * refinedT;
  3991. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  3992. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  3993. refinedT -= (x - t) * slope;
  3994. refinedT = Math.min(1, Math.max(0, refinedT));
  3995. }
  3996. // Resolve cubic bezier for the given x
  3997. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  3998. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  3999. Math.pow(refinedT, 3);
  4000. };
  4001. return BezierCurve;
  4002. }());
  4003. BABYLON.BezierCurve = BezierCurve;
  4004. var Orientation;
  4005. (function (Orientation) {
  4006. Orientation[Orientation["CW"] = 0] = "CW";
  4007. Orientation[Orientation["CCW"] = 1] = "CCW";
  4008. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4009. var Angle = (function () {
  4010. /**
  4011. * Creates an Angle object of "radians" radians (float).
  4012. */
  4013. function Angle(radians) {
  4014. var _this = this;
  4015. /**
  4016. * Returns the Angle value in degrees (float).
  4017. */
  4018. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4019. /**
  4020. * Returns the Angle value in radians (float).
  4021. */
  4022. this.radians = function () { return _this._radians; };
  4023. this._radians = radians;
  4024. if (this._radians < 0.0)
  4025. this._radians += (2.0 * Math.PI);
  4026. }
  4027. /**
  4028. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4029. */
  4030. Angle.BetweenTwoPoints = function (a, b) {
  4031. var delta = b.subtract(a);
  4032. var theta = Math.atan2(delta.y, delta.x);
  4033. return new Angle(theta);
  4034. };
  4035. /**
  4036. * Returns a new Angle object from the passed float in radians.
  4037. */
  4038. Angle.FromRadians = function (radians) {
  4039. return new Angle(radians);
  4040. };
  4041. /**
  4042. * Returns a new Angle object from the passed float in degrees.
  4043. */
  4044. Angle.FromDegrees = function (degrees) {
  4045. return new Angle(degrees * Math.PI / 180.0);
  4046. };
  4047. return Angle;
  4048. }());
  4049. BABYLON.Angle = Angle;
  4050. var Arc2 = (function () {
  4051. /**
  4052. * Creates an Arc object from the three passed points : start, middle and end.
  4053. */
  4054. function Arc2(startPoint, midPoint, endPoint) {
  4055. this.startPoint = startPoint;
  4056. this.midPoint = midPoint;
  4057. this.endPoint = endPoint;
  4058. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4059. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4060. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4061. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4062. 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);
  4063. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4064. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4065. var a1 = this.startAngle.degrees();
  4066. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4067. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4068. // angles correction
  4069. if (a2 - a1 > +180.0)
  4070. a2 -= 360.0;
  4071. if (a2 - a1 < -180.0)
  4072. a2 += 360.0;
  4073. if (a3 - a2 > +180.0)
  4074. a3 -= 360.0;
  4075. if (a3 - a2 < -180.0)
  4076. a3 += 360.0;
  4077. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4078. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4079. }
  4080. return Arc2;
  4081. }());
  4082. BABYLON.Arc2 = Arc2;
  4083. var Path2 = (function () {
  4084. /**
  4085. * Creates a Path2 object from the starting 2D coordinates x and y.
  4086. */
  4087. function Path2(x, y) {
  4088. this._points = new Array();
  4089. this._length = 0.0;
  4090. this.closed = false;
  4091. this._points.push(new Vector2(x, y));
  4092. }
  4093. /**
  4094. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4095. * Returns the updated Path2.
  4096. */
  4097. Path2.prototype.addLineTo = function (x, y) {
  4098. if (closed) {
  4099. //Tools.Error("cannot add lines to closed paths");
  4100. return this;
  4101. }
  4102. var newPoint = new Vector2(x, y);
  4103. var previousPoint = this._points[this._points.length - 1];
  4104. this._points.push(newPoint);
  4105. this._length += newPoint.subtract(previousPoint).length();
  4106. return this;
  4107. };
  4108. /**
  4109. * 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.
  4110. * Returns the updated Path2.
  4111. */
  4112. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4113. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4114. if (closed) {
  4115. //Tools.Error("cannot add arcs to closed paths");
  4116. return this;
  4117. }
  4118. var startPoint = this._points[this._points.length - 1];
  4119. var midPoint = new Vector2(midX, midY);
  4120. var endPoint = new Vector2(endX, endY);
  4121. var arc = new Arc2(startPoint, midPoint, endPoint);
  4122. var increment = arc.angle.radians() / numberOfSegments;
  4123. if (arc.orientation === Orientation.CW)
  4124. increment *= -1;
  4125. var currentAngle = arc.startAngle.radians() + increment;
  4126. for (var i = 0; i < numberOfSegments; i++) {
  4127. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4128. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4129. this.addLineTo(x, y);
  4130. currentAngle += increment;
  4131. }
  4132. return this;
  4133. };
  4134. /**
  4135. * Closes the Path2.
  4136. * Returns the Path2.
  4137. */
  4138. Path2.prototype.close = function () {
  4139. this.closed = true;
  4140. return this;
  4141. };
  4142. /**
  4143. * Returns the Path2 total length (float).
  4144. */
  4145. Path2.prototype.length = function () {
  4146. var result = this._length;
  4147. if (!this.closed) {
  4148. var lastPoint = this._points[this._points.length - 1];
  4149. var firstPoint = this._points[0];
  4150. result += (firstPoint.subtract(lastPoint).length());
  4151. }
  4152. return result;
  4153. };
  4154. /**
  4155. * Returns the Path2 internal array of points.
  4156. */
  4157. Path2.prototype.getPoints = function () {
  4158. return this._points;
  4159. };
  4160. /**
  4161. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4162. */
  4163. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4164. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4165. //Tools.Error("normalized length position should be between 0 and 1.");
  4166. return Vector2.Zero();
  4167. }
  4168. var lengthPosition = normalizedLengthPosition * this.length();
  4169. var previousOffset = 0;
  4170. for (var i = 0; i < this._points.length; i++) {
  4171. var j = (i + 1) % this._points.length;
  4172. var a = this._points[i];
  4173. var b = this._points[j];
  4174. var bToA = b.subtract(a);
  4175. var nextOffset = (bToA.length() + previousOffset);
  4176. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4177. var dir = bToA.normalize();
  4178. var localOffset = lengthPosition - previousOffset;
  4179. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4180. }
  4181. previousOffset = nextOffset;
  4182. }
  4183. //Tools.Error("internal error");
  4184. return Vector2.Zero();
  4185. };
  4186. /**
  4187. * Returns a new Path2 starting at the coordinates (x, y).
  4188. */
  4189. Path2.StartingAt = function (x, y) {
  4190. return new Path2(x, y);
  4191. };
  4192. return Path2;
  4193. }());
  4194. BABYLON.Path2 = Path2;
  4195. var Path3D = (function () {
  4196. /**
  4197. * new Path3D(path, normal, raw)
  4198. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4199. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4200. * path : an array of Vector3, the curve axis of the Path3D
  4201. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4202. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4203. */
  4204. function Path3D(path, firstNormal, raw) {
  4205. this.path = path;
  4206. this._curve = new Array();
  4207. this._distances = new Array();
  4208. this._tangents = new Array();
  4209. this._normals = new Array();
  4210. this._binormals = new Array();
  4211. for (var p = 0; p < path.length; p++) {
  4212. this._curve[p] = path[p].clone(); // hard copy
  4213. }
  4214. this._raw = raw || false;
  4215. this._compute(firstNormal);
  4216. }
  4217. /**
  4218. * Returns the Path3D array of successive Vector3 designing its curve.
  4219. */
  4220. Path3D.prototype.getCurve = function () {
  4221. return this._curve;
  4222. };
  4223. /**
  4224. * Returns an array populated with tangent vectors on each Path3D curve point.
  4225. */
  4226. Path3D.prototype.getTangents = function () {
  4227. return this._tangents;
  4228. };
  4229. /**
  4230. * Returns an array populated with normal vectors on each Path3D curve point.
  4231. */
  4232. Path3D.prototype.getNormals = function () {
  4233. return this._normals;
  4234. };
  4235. /**
  4236. * Returns an array populated with binormal vectors on each Path3D curve point.
  4237. */
  4238. Path3D.prototype.getBinormals = function () {
  4239. return this._binormals;
  4240. };
  4241. /**
  4242. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4243. */
  4244. Path3D.prototype.getDistances = function () {
  4245. return this._distances;
  4246. };
  4247. /**
  4248. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4249. * Returns the same object updated.
  4250. */
  4251. Path3D.prototype.update = function (path, firstNormal) {
  4252. for (var p = 0; p < path.length; p++) {
  4253. this._curve[p].x = path[p].x;
  4254. this._curve[p].y = path[p].y;
  4255. this._curve[p].z = path[p].z;
  4256. }
  4257. this._compute(firstNormal);
  4258. return this;
  4259. };
  4260. // private function compute() : computes tangents, normals and binormals
  4261. Path3D.prototype._compute = function (firstNormal) {
  4262. var l = this._curve.length;
  4263. // first and last tangents
  4264. this._tangents[0] = this._getFirstNonNullVector(0);
  4265. if (!this._raw) {
  4266. this._tangents[0].normalize();
  4267. }
  4268. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4269. if (!this._raw) {
  4270. this._tangents[l - 1].normalize();
  4271. }
  4272. // normals and binormals at first point : arbitrary vector with _normalVector()
  4273. var tg0 = this._tangents[0];
  4274. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4275. this._normals[0] = pp0;
  4276. if (!this._raw) {
  4277. this._normals[0].normalize();
  4278. }
  4279. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4280. if (!this._raw) {
  4281. this._binormals[0].normalize();
  4282. }
  4283. this._distances[0] = 0.0;
  4284. // normals and binormals : next points
  4285. var prev; // previous vector (segment)
  4286. var cur; // current vector (segment)
  4287. var curTang; // current tangent
  4288. // previous normal
  4289. var prevBinor; // previous binormal
  4290. for (var i = 1; i < l; i++) {
  4291. // tangents
  4292. prev = this._getLastNonNullVector(i);
  4293. if (i < l - 1) {
  4294. cur = this._getFirstNonNullVector(i);
  4295. this._tangents[i] = prev.add(cur);
  4296. this._tangents[i].normalize();
  4297. }
  4298. this._distances[i] = this._distances[i - 1] + prev.length();
  4299. // normals and binormals
  4300. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4301. curTang = this._tangents[i];
  4302. prevBinor = this._binormals[i - 1];
  4303. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4304. if (!this._raw) {
  4305. this._normals[i].normalize();
  4306. }
  4307. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4308. if (!this._raw) {
  4309. this._binormals[i].normalize();
  4310. }
  4311. }
  4312. };
  4313. // private function getFirstNonNullVector(index)
  4314. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4315. Path3D.prototype._getFirstNonNullVector = function (index) {
  4316. var i = 1;
  4317. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4318. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4319. i++;
  4320. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4321. }
  4322. return nNVector;
  4323. };
  4324. // private function getLastNonNullVector(index)
  4325. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4326. Path3D.prototype._getLastNonNullVector = function (index) {
  4327. var i = 1;
  4328. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4329. while (nLVector.length() === 0 && index > i + 1) {
  4330. i++;
  4331. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4332. }
  4333. return nLVector;
  4334. };
  4335. // private function normalVector(v0, vt, va) :
  4336. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4337. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4338. Path3D.prototype._normalVector = function (v0, vt, va) {
  4339. var normal0;
  4340. var tgl = vt.length();
  4341. if (tgl === 0.0) {
  4342. tgl = 1.0;
  4343. }
  4344. if (va === undefined || va === null) {
  4345. var point;
  4346. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4347. point = new Vector3(0.0, -1.0, 0.0);
  4348. }
  4349. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4350. point = new Vector3(1.0, 0.0, 0.0);
  4351. }
  4352. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4353. point = new Vector3(0.0, 0.0, 1.0);
  4354. }
  4355. normal0 = Vector3.Cross(vt, point);
  4356. }
  4357. else {
  4358. normal0 = Vector3.Cross(vt, va);
  4359. Vector3.CrossToRef(normal0, vt, normal0);
  4360. }
  4361. normal0.normalize();
  4362. return normal0;
  4363. };
  4364. return Path3D;
  4365. }());
  4366. BABYLON.Path3D = Path3D;
  4367. var Curve3 = (function () {
  4368. /**
  4369. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4370. * A Curve3 is designed from a series of successive Vector3.
  4371. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4372. */
  4373. function Curve3(points) {
  4374. this._length = 0.0;
  4375. this._points = points;
  4376. this._length = this._computeLength(points);
  4377. }
  4378. /**
  4379. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4380. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4381. * @param v1 (Vector3) the control point
  4382. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4383. * @param nbPoints (integer) the wanted number of points in the curve
  4384. */
  4385. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4386. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4387. var bez = new Array();
  4388. var equation = function (t, val0, val1, val2) {
  4389. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4390. return res;
  4391. };
  4392. for (var i = 0; i <= nbPoints; i++) {
  4393. 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)));
  4394. }
  4395. return new Curve3(bez);
  4396. };
  4397. /**
  4398. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4399. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4400. * @param v1 (Vector3) the first control point
  4401. * @param v2 (Vector3) the second control point
  4402. * @param v3 (Vector3) the end point of the Cubic Bezier
  4403. * @param nbPoints (integer) the wanted number of points in the curve
  4404. */
  4405. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4406. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4407. var bez = new Array();
  4408. var equation = function (t, val0, val1, val2, val3) {
  4409. 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;
  4410. return res;
  4411. };
  4412. for (var i = 0; i <= nbPoints; i++) {
  4413. 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)));
  4414. }
  4415. return new Curve3(bez);
  4416. };
  4417. /**
  4418. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4419. * @param p1 (Vector3) the origin point of the Hermite Spline
  4420. * @param t1 (Vector3) the tangent vector at the origin point
  4421. * @param p2 (Vector3) the end point of the Hermite Spline
  4422. * @param t2 (Vector3) the tangent vector at the end point
  4423. * @param nbPoints (integer) the wanted number of points in the curve
  4424. */
  4425. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4426. var hermite = new Array();
  4427. var step = 1.0 / nbPoints;
  4428. for (var i = 0; i <= nbPoints; i++) {
  4429. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4430. }
  4431. return new Curve3(hermite);
  4432. };
  4433. /**
  4434. * Returns a Curve3 object along a CatmullRom Spline curve :
  4435. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4436. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4437. */
  4438. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4439. var totalPoints = new Array();
  4440. totalPoints.push(points[0].clone());
  4441. Array.prototype.push.apply(totalPoints, points);
  4442. totalPoints.push(points[points.length - 1].clone());
  4443. var catmullRom = new Array();
  4444. var step = 1.0 / nbPoints;
  4445. for (var i = 0; i < totalPoints.length - 3; i++) {
  4446. var amount = 0.0;
  4447. for (var c = 0; c < nbPoints; c++) {
  4448. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4449. amount += step;
  4450. }
  4451. }
  4452. i--;
  4453. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4454. return new Curve3(catmullRom);
  4455. };
  4456. /**
  4457. * Returns the Curve3 stored array of successive Vector3
  4458. */
  4459. Curve3.prototype.getPoints = function () {
  4460. return this._points;
  4461. };
  4462. /**
  4463. * Returns the computed length (float) of the curve.
  4464. */
  4465. Curve3.prototype.length = function () {
  4466. return this._length;
  4467. };
  4468. /**
  4469. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4470. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4471. * curveA and curveB keep unchanged.
  4472. */
  4473. Curve3.prototype.continue = function (curve) {
  4474. var lastPoint = this._points[this._points.length - 1];
  4475. var continuedPoints = this._points.slice();
  4476. var curvePoints = curve.getPoints();
  4477. for (var i = 1; i < curvePoints.length; i++) {
  4478. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4479. }
  4480. var continuedCurve = new Curve3(continuedPoints);
  4481. return continuedCurve;
  4482. };
  4483. Curve3.prototype._computeLength = function (path) {
  4484. var l = 0;
  4485. for (var i = 1; i < path.length; i++) {
  4486. l += (path[i].subtract(path[i - 1])).length();
  4487. }
  4488. return l;
  4489. };
  4490. return Curve3;
  4491. }());
  4492. BABYLON.Curve3 = Curve3;
  4493. // SphericalHarmonics
  4494. var SphericalHarmonics = (function () {
  4495. function SphericalHarmonics() {
  4496. this.L00 = Vector3.Zero();
  4497. this.L1_1 = Vector3.Zero();
  4498. this.L10 = Vector3.Zero();
  4499. this.L11 = Vector3.Zero();
  4500. this.L2_2 = Vector3.Zero();
  4501. this.L2_1 = Vector3.Zero();
  4502. this.L20 = Vector3.Zero();
  4503. this.L21 = Vector3.Zero();
  4504. this.L22 = Vector3.Zero();
  4505. }
  4506. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4507. var colorVector = new Vector3(color.r, color.g, color.b);
  4508. var c = colorVector.scale(deltaSolidAngle);
  4509. this.L00 = this.L00.add(c.scale(0.282095));
  4510. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4511. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4512. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4513. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4514. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4515. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4516. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4517. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4518. };
  4519. SphericalHarmonics.prototype.scale = function (scale) {
  4520. this.L00 = this.L00.scale(scale);
  4521. this.L1_1 = this.L1_1.scale(scale);
  4522. this.L10 = this.L10.scale(scale);
  4523. this.L11 = this.L11.scale(scale);
  4524. this.L2_2 = this.L2_2.scale(scale);
  4525. this.L2_1 = this.L2_1.scale(scale);
  4526. this.L20 = this.L20.scale(scale);
  4527. this.L21 = this.L21.scale(scale);
  4528. this.L22 = this.L22.scale(scale);
  4529. };
  4530. return SphericalHarmonics;
  4531. }());
  4532. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4533. // SphericalPolynomial
  4534. var SphericalPolynomial = (function () {
  4535. function SphericalPolynomial() {
  4536. this.x = Vector3.Zero();
  4537. this.y = Vector3.Zero();
  4538. this.z = Vector3.Zero();
  4539. this.xx = Vector3.Zero();
  4540. this.yy = Vector3.Zero();
  4541. this.zz = Vector3.Zero();
  4542. this.xy = Vector3.Zero();
  4543. this.yz = Vector3.Zero();
  4544. this.zx = Vector3.Zero();
  4545. }
  4546. SphericalPolynomial.prototype.addAmbient = function (color) {
  4547. var colorVector = new Vector3(color.r, color.g, color.b);
  4548. this.xx = this.xx.add(colorVector);
  4549. this.yy = this.yy.add(colorVector);
  4550. this.zz = this.zz.add(colorVector);
  4551. };
  4552. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4553. var result = new SphericalPolynomial();
  4554. result.x = harmonics.L11.scale(1.02333);
  4555. result.y = harmonics.L1_1.scale(1.02333);
  4556. result.z = harmonics.L10.scale(1.02333);
  4557. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4558. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4559. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4560. result.yz = harmonics.L2_1.scale(0.858086);
  4561. result.zx = harmonics.L21.scale(0.858086);
  4562. result.xy = harmonics.L2_2.scale(0.858086);
  4563. return result;
  4564. };
  4565. return SphericalPolynomial;
  4566. }());
  4567. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4568. // Vertex formats
  4569. var PositionNormalVertex = (function () {
  4570. function PositionNormalVertex(position, normal) {
  4571. if (position === void 0) { position = Vector3.Zero(); }
  4572. if (normal === void 0) { normal = Vector3.Up(); }
  4573. this.position = position;
  4574. this.normal = normal;
  4575. }
  4576. PositionNormalVertex.prototype.clone = function () {
  4577. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4578. };
  4579. return PositionNormalVertex;
  4580. }());
  4581. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4582. var PositionNormalTextureVertex = (function () {
  4583. function PositionNormalTextureVertex(position, normal, uv) {
  4584. if (position === void 0) { position = Vector3.Zero(); }
  4585. if (normal === void 0) { normal = Vector3.Up(); }
  4586. if (uv === void 0) { uv = Vector2.Zero(); }
  4587. this.position = position;
  4588. this.normal = normal;
  4589. this.uv = uv;
  4590. }
  4591. PositionNormalTextureVertex.prototype.clone = function () {
  4592. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4593. };
  4594. return PositionNormalTextureVertex;
  4595. }());
  4596. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4597. // Temporary pre-allocated objects for engine internal use
  4598. // usage in any internal function :
  4599. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4600. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4601. var Tmp = (function () {
  4602. function Tmp() {
  4603. }
  4604. return Tmp;
  4605. }());
  4606. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4607. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4608. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4609. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4610. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4611. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4612. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4613. Matrix.Zero(), Matrix.Zero(),
  4614. Matrix.Zero(), Matrix.Zero(),
  4615. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4616. BABYLON.Tmp = Tmp;
  4617. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4618. var MathTmp = (function () {
  4619. function MathTmp() {
  4620. }
  4621. return MathTmp;
  4622. }());
  4623. MathTmp.Vector3 = [Vector3.Zero()];
  4624. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4625. MathTmp.Quaternion = [Quaternion.Zero()];
  4626. })(BABYLON || (BABYLON = {}));
  4627. //# sourceMappingURL=babylon.math.js.map
  4628. //# sourceMappingURL=babylon.mixins.js.map
  4629. var BABYLON;
  4630. (function (BABYLON) {
  4631. function generateSerializableMember(type, sourceName) {
  4632. return function (target, propertyKey) {
  4633. if (!target.__serializableMembers) {
  4634. target.__serializableMembers = {};
  4635. }
  4636. if (!target.__serializableMembers[propertyKey]) {
  4637. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4638. }
  4639. };
  4640. }
  4641. function serialize(sourceName) {
  4642. return generateSerializableMember(0, sourceName); // value member
  4643. }
  4644. BABYLON.serialize = serialize;
  4645. function serializeAsTexture(sourceName) {
  4646. return generateSerializableMember(1, sourceName); // texture member
  4647. }
  4648. BABYLON.serializeAsTexture = serializeAsTexture;
  4649. function serializeAsColor3(sourceName) {
  4650. return generateSerializableMember(2, sourceName); // color3 member
  4651. }
  4652. BABYLON.serializeAsColor3 = serializeAsColor3;
  4653. function serializeAsFresnelParameters(sourceName) {
  4654. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4655. }
  4656. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4657. function serializeAsVector2(sourceName) {
  4658. return generateSerializableMember(4, sourceName); // vector2 member
  4659. }
  4660. BABYLON.serializeAsVector2 = serializeAsVector2;
  4661. function serializeAsVector3(sourceName) {
  4662. return generateSerializableMember(5, sourceName); // vector3 member
  4663. }
  4664. BABYLON.serializeAsVector3 = serializeAsVector3;
  4665. function serializeAsMeshReference(sourceName) {
  4666. return generateSerializableMember(6, sourceName); // mesh reference member
  4667. }
  4668. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4669. function serializeAsColorCurves(sourceName) {
  4670. return generateSerializableMember(7, sourceName); // color curves
  4671. }
  4672. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4673. var SerializationHelper = (function () {
  4674. function SerializationHelper() {
  4675. }
  4676. SerializationHelper.Serialize = function (entity, serializationObject) {
  4677. if (!serializationObject) {
  4678. serializationObject = {};
  4679. }
  4680. // Tags
  4681. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4682. // Properties
  4683. for (var property in entity.__serializableMembers) {
  4684. var propertyDescriptor = entity.__serializableMembers[property];
  4685. var targetPropertyName = propertyDescriptor.sourceName || property;
  4686. var propertyType = propertyDescriptor.type;
  4687. var sourceProperty = entity[property];
  4688. if (sourceProperty !== undefined && sourceProperty !== null) {
  4689. switch (propertyType) {
  4690. case 0:
  4691. serializationObject[targetPropertyName] = sourceProperty;
  4692. break;
  4693. case 1:
  4694. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4695. break;
  4696. case 2:
  4697. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4698. break;
  4699. case 3:
  4700. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4701. break;
  4702. case 4:
  4703. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4704. break;
  4705. case 5:
  4706. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4707. break;
  4708. case 6:
  4709. serializationObject[targetPropertyName] = sourceProperty.id;
  4710. break;
  4711. case 7:
  4712. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4713. break;
  4714. }
  4715. }
  4716. }
  4717. return serializationObject;
  4718. };
  4719. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4720. var destination = creationFunction();
  4721. // Tags
  4722. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4723. // Properties
  4724. for (var property in destination.__serializableMembers) {
  4725. var propertyDescriptor = destination.__serializableMembers[property];
  4726. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4727. var propertyType = propertyDescriptor.type;
  4728. if (sourceProperty !== undefined && sourceProperty !== null) {
  4729. switch (propertyType) {
  4730. case 0:
  4731. destination[property] = sourceProperty;
  4732. break;
  4733. case 1:
  4734. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4735. break;
  4736. case 2:
  4737. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4738. break;
  4739. case 3:
  4740. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4741. break;
  4742. case 4:
  4743. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4744. break;
  4745. case 5:
  4746. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4747. break;
  4748. case 6:
  4749. destination[property] = scene.getLastMeshByID(sourceProperty);
  4750. break;
  4751. case 7:
  4752. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4753. break;
  4754. }
  4755. }
  4756. }
  4757. return destination;
  4758. };
  4759. SerializationHelper.Clone = function (creationFunction, source) {
  4760. var destination = creationFunction();
  4761. // Tags
  4762. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4763. // Properties
  4764. for (var property in destination.__serializableMembers) {
  4765. var propertyDescriptor = destination.__serializableMembers[property];
  4766. var sourceProperty = source[property];
  4767. var propertyType = propertyDescriptor.type;
  4768. if (sourceProperty !== undefined && sourceProperty !== null) {
  4769. switch (propertyType) {
  4770. case 0: // Value
  4771. case 6:
  4772. destination[property] = sourceProperty;
  4773. break;
  4774. case 1: // Texture
  4775. case 2: // Color3
  4776. case 3: // FresnelParameters
  4777. case 4: // Vector2
  4778. case 5: // Vector3
  4779. case 7:
  4780. destination[property] = sourceProperty.clone();
  4781. break;
  4782. }
  4783. }
  4784. }
  4785. return destination;
  4786. };
  4787. return SerializationHelper;
  4788. }());
  4789. BABYLON.SerializationHelper = SerializationHelper;
  4790. })(BABYLON || (BABYLON = {}));
  4791. //# sourceMappingURL=babylon.decorators.js.map
  4792. var BABYLON;
  4793. (function (BABYLON) {
  4794. /**
  4795. * A class serves as a medium between the observable and its observers
  4796. */
  4797. var EventState = (function () {
  4798. /**
  4799. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4800. */
  4801. function EventState(mask, skipNextObservers) {
  4802. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4803. this.initalize(mask, skipNextObservers);
  4804. }
  4805. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4806. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4807. this.mask = mask;
  4808. this.skipNextObservers = skipNextObservers;
  4809. return this;
  4810. };
  4811. return EventState;
  4812. }());
  4813. BABYLON.EventState = EventState;
  4814. /**
  4815. * Represent an Observer registered to a given Observable object.
  4816. */
  4817. var Observer = (function () {
  4818. function Observer(callback, mask) {
  4819. this.callback = callback;
  4820. this.mask = mask;
  4821. }
  4822. return Observer;
  4823. }());
  4824. BABYLON.Observer = Observer;
  4825. /**
  4826. * The Observable class is a simple implementation of the Observable pattern.
  4827. * 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.
  4828. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4829. * 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).
  4830. * 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.
  4831. */
  4832. var Observable = (function () {
  4833. function Observable() {
  4834. this._observers = new Array();
  4835. this._eventState = new EventState(0);
  4836. }
  4837. /**
  4838. * Create a new Observer with the specified callback
  4839. * @param callback the callback that will be executed for that Observer
  4840. * @param mask the mask used to filter observers
  4841. * @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.
  4842. */
  4843. Observable.prototype.add = function (callback, mask, insertFirst) {
  4844. if (mask === void 0) { mask = -1; }
  4845. if (insertFirst === void 0) { insertFirst = false; }
  4846. if (!callback) {
  4847. return null;
  4848. }
  4849. var observer = new Observer(callback, mask);
  4850. if (insertFirst) {
  4851. this._observers.unshift(observer);
  4852. }
  4853. else {
  4854. this._observers.push(observer);
  4855. }
  4856. return observer;
  4857. };
  4858. /**
  4859. * Remove an Observer from the Observable object
  4860. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4861. */
  4862. Observable.prototype.remove = function (observer) {
  4863. var index = this._observers.indexOf(observer);
  4864. if (index !== -1) {
  4865. this._observers.splice(index, 1);
  4866. return true;
  4867. }
  4868. return false;
  4869. };
  4870. /**
  4871. * Remove a callback from the Observable object
  4872. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4873. */
  4874. Observable.prototype.removeCallback = function (callback) {
  4875. for (var index = 0; index < this._observers.length; index++) {
  4876. if (this._observers[index].callback === callback) {
  4877. this._observers.splice(index, 1);
  4878. return true;
  4879. }
  4880. }
  4881. return false;
  4882. };
  4883. /**
  4884. * Notify all Observers by calling their respective callback with the given data
  4885. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4886. * @param eventData
  4887. * @param mask
  4888. */
  4889. Observable.prototype.notifyObservers = function (eventData, mask) {
  4890. if (mask === void 0) { mask = -1; }
  4891. var state = this._eventState;
  4892. state.mask = mask;
  4893. state.skipNextObservers = false;
  4894. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4895. var obs = _a[_i];
  4896. if (obs.mask & mask) {
  4897. obs.callback(eventData, state);
  4898. }
  4899. if (state.skipNextObservers) {
  4900. return false;
  4901. }
  4902. }
  4903. return true;
  4904. };
  4905. /**
  4906. * return true is the Observable has at least one Observer registered
  4907. */
  4908. Observable.prototype.hasObservers = function () {
  4909. return this._observers.length > 0;
  4910. };
  4911. /**
  4912. * Clear the list of observers
  4913. */
  4914. Observable.prototype.clear = function () {
  4915. this._observers = new Array();
  4916. };
  4917. /**
  4918. * Clone the current observable
  4919. */
  4920. Observable.prototype.clone = function () {
  4921. var result = new Observable();
  4922. result._observers = this._observers.slice(0);
  4923. return result;
  4924. };
  4925. return Observable;
  4926. }());
  4927. BABYLON.Observable = Observable;
  4928. })(BABYLON || (BABYLON = {}));
  4929. //# sourceMappingURL=babylon.observable.js.map
  4930. var BABYLON;
  4931. (function (BABYLON) {
  4932. var Database = (function () {
  4933. function Database(urlToScene, callbackManifestChecked) {
  4934. // Handling various flavors of prefixed version of IndexedDB
  4935. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4936. this.callbackManifestChecked = callbackManifestChecked;
  4937. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4938. this.db = null;
  4939. this.enableSceneOffline = false;
  4940. this.enableTexturesOffline = false;
  4941. this.manifestVersionFound = 0;
  4942. this.mustUpdateRessources = false;
  4943. this.hasReachedQuota = false;
  4944. if (!Database.IDBStorageEnabled) {
  4945. this.callbackManifestChecked(true);
  4946. }
  4947. else {
  4948. this.checkManifestFile();
  4949. }
  4950. }
  4951. Database.prototype.checkManifestFile = function () {
  4952. var _this = this;
  4953. function noManifestFile() {
  4954. that.enableSceneOffline = false;
  4955. that.enableTexturesOffline = false;
  4956. that.callbackManifestChecked(false);
  4957. }
  4958. var that = this;
  4959. var timeStampUsed = false;
  4960. var manifestURL = this.currentSceneUrl + ".manifest";
  4961. var xhr = new XMLHttpRequest();
  4962. if (navigator.onLine) {
  4963. // Adding a timestamp to by-pass browsers' cache
  4964. timeStampUsed = true;
  4965. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  4966. }
  4967. xhr.open("GET", manifestURL, true);
  4968. xhr.addEventListener("load", function () {
  4969. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  4970. try {
  4971. var manifestFile = JSON.parse(xhr.response);
  4972. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  4973. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  4974. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  4975. _this.manifestVersionFound = manifestFile.version;
  4976. }
  4977. if (_this.callbackManifestChecked) {
  4978. _this.callbackManifestChecked(true);
  4979. }
  4980. }
  4981. catch (ex) {
  4982. noManifestFile();
  4983. }
  4984. }
  4985. else {
  4986. noManifestFile();
  4987. }
  4988. }, false);
  4989. xhr.addEventListener("error", function (event) {
  4990. if (timeStampUsed) {
  4991. timeStampUsed = false;
  4992. // Let's retry without the timeStamp
  4993. // It could fail when coupled with HTML5 Offline API
  4994. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  4995. xhr.open("GET", retryManifestURL, true);
  4996. xhr.send();
  4997. }
  4998. else {
  4999. noManifestFile();
  5000. }
  5001. }, false);
  5002. try {
  5003. xhr.send();
  5004. }
  5005. catch (ex) {
  5006. BABYLON.Tools.Error("Error on XHR send request.");
  5007. that.callbackManifestChecked(false);
  5008. }
  5009. };
  5010. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5011. var _this = this;
  5012. function handleError() {
  5013. that.isSupported = false;
  5014. if (errorCallback)
  5015. errorCallback();
  5016. }
  5017. var that = this;
  5018. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5019. // Your browser doesn't support IndexedDB
  5020. this.isSupported = false;
  5021. if (errorCallback)
  5022. errorCallback();
  5023. }
  5024. else {
  5025. // If the DB hasn't been opened or created yet
  5026. if (!this.db) {
  5027. this.hasReachedQuota = false;
  5028. this.isSupported = true;
  5029. var request = this.idbFactory.open("babylonjs", 1);
  5030. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5031. request.onerror = function (event) {
  5032. handleError();
  5033. };
  5034. // executes when a version change transaction cannot complete due to other active transactions
  5035. request.onblocked = function (event) {
  5036. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5037. handleError();
  5038. };
  5039. // DB has been opened successfully
  5040. request.onsuccess = function (event) {
  5041. _this.db = request.result;
  5042. successCallback();
  5043. };
  5044. // Initialization of the DB. Creating Scenes & Textures stores
  5045. request.onupgradeneeded = function (event) {
  5046. _this.db = (event.target).result;
  5047. try {
  5048. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5049. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5050. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5051. }
  5052. catch (ex) {
  5053. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5054. handleError();
  5055. }
  5056. };
  5057. }
  5058. else {
  5059. if (successCallback)
  5060. successCallback();
  5061. }
  5062. }
  5063. };
  5064. Database.prototype.loadImageFromDB = function (url, image) {
  5065. var _this = this;
  5066. var completeURL = Database.ReturnFullUrlLocation(url);
  5067. var saveAndLoadImage = function () {
  5068. if (!_this.hasReachedQuota && _this.db !== null) {
  5069. // the texture is not yet in the DB, let's try to save it
  5070. _this._saveImageIntoDBAsync(completeURL, image);
  5071. }
  5072. else {
  5073. image.src = url;
  5074. }
  5075. };
  5076. if (!this.mustUpdateRessources) {
  5077. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5078. }
  5079. else {
  5080. saveAndLoadImage();
  5081. }
  5082. };
  5083. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5084. if (this.isSupported && this.db !== null) {
  5085. var texture;
  5086. var transaction = this.db.transaction(["textures"]);
  5087. transaction.onabort = function (event) {
  5088. image.src = url;
  5089. };
  5090. transaction.oncomplete = function (event) {
  5091. var blobTextureURL;
  5092. if (texture) {
  5093. var URL = window.URL || window.webkitURL;
  5094. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5095. image.onerror = function () {
  5096. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5097. image.src = url;
  5098. };
  5099. image.src = blobTextureURL;
  5100. }
  5101. else {
  5102. notInDBCallback();
  5103. }
  5104. };
  5105. var getRequest = transaction.objectStore("textures").get(url);
  5106. getRequest.onsuccess = function (event) {
  5107. texture = (event.target).result;
  5108. };
  5109. getRequest.onerror = function (event) {
  5110. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5111. image.src = url;
  5112. };
  5113. }
  5114. else {
  5115. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5116. image.src = url;
  5117. }
  5118. };
  5119. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5120. var _this = this;
  5121. if (this.isSupported) {
  5122. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5123. var generateBlobUrl = function () {
  5124. var blobTextureURL;
  5125. if (blob) {
  5126. var URL = window.URL || window.webkitURL;
  5127. try {
  5128. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5129. }
  5130. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5131. catch (ex) {
  5132. blobTextureURL = URL.createObjectURL(blob);
  5133. }
  5134. }
  5135. image.src = blobTextureURL;
  5136. };
  5137. if (Database.IsUASupportingBlobStorage) {
  5138. var xhr = new XMLHttpRequest(), blob;
  5139. xhr.open("GET", url, true);
  5140. xhr.responseType = "blob";
  5141. xhr.addEventListener("load", function () {
  5142. if (xhr.status === 200) {
  5143. // Blob as response (XHR2)
  5144. blob = xhr.response;
  5145. var transaction = _this.db.transaction(["textures"], "readwrite");
  5146. // the transaction could abort because of a QuotaExceededError error
  5147. transaction.onabort = function (event) {
  5148. try {
  5149. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5150. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5151. _this.hasReachedQuota = true;
  5152. }
  5153. }
  5154. catch (ex) { }
  5155. generateBlobUrl();
  5156. };
  5157. transaction.oncomplete = function (event) {
  5158. generateBlobUrl();
  5159. };
  5160. var newTexture = { textureUrl: url, data: blob };
  5161. try {
  5162. // Put the blob into the dabase
  5163. var addRequest = transaction.objectStore("textures").put(newTexture);
  5164. addRequest.onsuccess = function (event) {
  5165. };
  5166. addRequest.onerror = function (event) {
  5167. generateBlobUrl();
  5168. };
  5169. }
  5170. catch (ex) {
  5171. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5172. if (ex.code === 25) {
  5173. Database.IsUASupportingBlobStorage = false;
  5174. }
  5175. image.src = url;
  5176. }
  5177. }
  5178. else {
  5179. image.src = url;
  5180. }
  5181. }, false);
  5182. xhr.addEventListener("error", function (event) {
  5183. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5184. image.src = url;
  5185. }, false);
  5186. xhr.send();
  5187. }
  5188. else {
  5189. image.src = url;
  5190. }
  5191. }
  5192. else {
  5193. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5194. image.src = url;
  5195. }
  5196. };
  5197. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5198. var _this = this;
  5199. var updateVersion = function (event) {
  5200. // the version is not yet in the DB or we need to update it
  5201. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5202. };
  5203. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5204. };
  5205. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5206. var _this = this;
  5207. if (this.isSupported) {
  5208. var version;
  5209. try {
  5210. var transaction = this.db.transaction(["versions"]);
  5211. transaction.oncomplete = function (event) {
  5212. if (version) {
  5213. // If the version in the JSON file is > than the version in DB
  5214. if (_this.manifestVersionFound > version.data) {
  5215. _this.mustUpdateRessources = true;
  5216. updateInDBCallback();
  5217. }
  5218. else {
  5219. callback(version.data);
  5220. }
  5221. }
  5222. else {
  5223. _this.mustUpdateRessources = true;
  5224. updateInDBCallback();
  5225. }
  5226. };
  5227. transaction.onabort = function (event) {
  5228. callback(-1);
  5229. };
  5230. var getRequest = transaction.objectStore("versions").get(url);
  5231. getRequest.onsuccess = function (event) {
  5232. version = (event.target).result;
  5233. };
  5234. getRequest.onerror = function (event) {
  5235. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5236. callback(-1);
  5237. };
  5238. }
  5239. catch (ex) {
  5240. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5241. callback(-1);
  5242. }
  5243. }
  5244. else {
  5245. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5246. callback(-1);
  5247. }
  5248. };
  5249. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5250. var _this = this;
  5251. if (this.isSupported && !this.hasReachedQuota) {
  5252. try {
  5253. // Open a transaction to the database
  5254. var transaction = this.db.transaction(["versions"], "readwrite");
  5255. // the transaction could abort because of a QuotaExceededError error
  5256. transaction.onabort = function (event) {
  5257. try {
  5258. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5259. _this.hasReachedQuota = true;
  5260. }
  5261. }
  5262. catch (ex) { }
  5263. callback(-1);
  5264. };
  5265. transaction.oncomplete = function (event) {
  5266. callback(_this.manifestVersionFound);
  5267. };
  5268. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5269. // Put the scene into the database
  5270. var addRequest = transaction.objectStore("versions").put(newVersion);
  5271. addRequest.onsuccess = function (event) {
  5272. };
  5273. addRequest.onerror = function (event) {
  5274. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5275. };
  5276. }
  5277. catch (ex) {
  5278. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5279. callback(-1);
  5280. }
  5281. }
  5282. else {
  5283. callback(-1);
  5284. }
  5285. };
  5286. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5287. var _this = this;
  5288. var completeUrl = Database.ReturnFullUrlLocation(url);
  5289. var saveAndLoadFile = function (event) {
  5290. // the scene is not yet in the DB, let's try to save it
  5291. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5292. };
  5293. this._checkVersionFromDB(completeUrl, function (version) {
  5294. if (version !== -1) {
  5295. if (!_this.mustUpdateRessources) {
  5296. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5297. }
  5298. else {
  5299. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5300. }
  5301. }
  5302. else {
  5303. errorCallback();
  5304. }
  5305. });
  5306. };
  5307. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5308. if (this.isSupported) {
  5309. var targetStore;
  5310. if (url.indexOf(".babylon") !== -1) {
  5311. targetStore = "scenes";
  5312. }
  5313. else {
  5314. targetStore = "textures";
  5315. }
  5316. var file;
  5317. var transaction = this.db.transaction([targetStore]);
  5318. transaction.oncomplete = function (event) {
  5319. if (file) {
  5320. callback(file.data);
  5321. }
  5322. else {
  5323. notInDBCallback();
  5324. }
  5325. };
  5326. transaction.onabort = function (event) {
  5327. notInDBCallback();
  5328. };
  5329. var getRequest = transaction.objectStore(targetStore).get(url);
  5330. getRequest.onsuccess = function (event) {
  5331. file = (event.target).result;
  5332. };
  5333. getRequest.onerror = function (event) {
  5334. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5335. notInDBCallback();
  5336. };
  5337. }
  5338. else {
  5339. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5340. callback();
  5341. }
  5342. };
  5343. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5344. var _this = this;
  5345. if (this.isSupported) {
  5346. var targetStore;
  5347. if (url.indexOf(".babylon") !== -1) {
  5348. targetStore = "scenes";
  5349. }
  5350. else {
  5351. targetStore = "textures";
  5352. }
  5353. // Create XHR
  5354. var xhr = new XMLHttpRequest(), fileData;
  5355. xhr.open("GET", url, true);
  5356. if (useArrayBuffer) {
  5357. xhr.responseType = "arraybuffer";
  5358. }
  5359. xhr.onprogress = progressCallback;
  5360. xhr.addEventListener("load", function () {
  5361. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5362. // Blob as response (XHR2)
  5363. //fileData = xhr.responseText;
  5364. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5365. if (!_this.hasReachedQuota) {
  5366. // Open a transaction to the database
  5367. var transaction = _this.db.transaction([targetStore], "readwrite");
  5368. // the transaction could abort because of a QuotaExceededError error
  5369. transaction.onabort = function (event) {
  5370. try {
  5371. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5372. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5373. _this.hasReachedQuota = true;
  5374. }
  5375. }
  5376. catch (ex) { }
  5377. callback(fileData);
  5378. };
  5379. transaction.oncomplete = function (event) {
  5380. callback(fileData);
  5381. };
  5382. var newFile;
  5383. if (targetStore === "scenes") {
  5384. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5385. }
  5386. else {
  5387. newFile = { textureUrl: url, data: fileData };
  5388. }
  5389. try {
  5390. // Put the scene into the database
  5391. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5392. addRequest.onsuccess = function (event) {
  5393. };
  5394. addRequest.onerror = function (event) {
  5395. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5396. };
  5397. }
  5398. catch (ex) {
  5399. callback(fileData);
  5400. }
  5401. }
  5402. else {
  5403. callback(fileData);
  5404. }
  5405. }
  5406. else {
  5407. callback();
  5408. }
  5409. }, false);
  5410. xhr.addEventListener("error", function (event) {
  5411. BABYLON.Tools.Error("error on XHR request.");
  5412. callback();
  5413. }, false);
  5414. xhr.send();
  5415. }
  5416. else {
  5417. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5418. callback();
  5419. }
  5420. };
  5421. return Database;
  5422. }());
  5423. Database.IsUASupportingBlobStorage = true;
  5424. Database.IDBStorageEnabled = true;
  5425. Database.parseURL = function (url) {
  5426. var a = document.createElement('a');
  5427. a.href = url;
  5428. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5429. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5430. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5431. return absLocation;
  5432. };
  5433. Database.ReturnFullUrlLocation = function (url) {
  5434. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5435. return (Database.parseURL(window.location.href) + url);
  5436. }
  5437. else {
  5438. return url;
  5439. }
  5440. };
  5441. BABYLON.Database = Database;
  5442. })(BABYLON || (BABYLON = {}));
  5443. //# sourceMappingURL=babylon.database.js.map
  5444. var BABYLON;
  5445. (function (BABYLON) {
  5446. var Internals;
  5447. (function (Internals) {
  5448. /*
  5449. * Based on jsTGALoader - Javascript loader for TGA file
  5450. * By Vincent Thibault
  5451. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5452. */
  5453. var TGATools = (function () {
  5454. function TGATools() {
  5455. }
  5456. TGATools.GetTGAHeader = function (data) {
  5457. var offset = 0;
  5458. var header = {
  5459. id_length: data[offset++],
  5460. colormap_type: data[offset++],
  5461. image_type: data[offset++],
  5462. colormap_index: data[offset++] | data[offset++] << 8,
  5463. colormap_length: data[offset++] | data[offset++] << 8,
  5464. colormap_size: data[offset++],
  5465. origin: [
  5466. data[offset++] | data[offset++] << 8,
  5467. data[offset++] | data[offset++] << 8
  5468. ],
  5469. width: data[offset++] | data[offset++] << 8,
  5470. height: data[offset++] | data[offset++] << 8,
  5471. pixel_size: data[offset++],
  5472. flags: data[offset++]
  5473. };
  5474. return header;
  5475. };
  5476. TGATools.UploadContent = function (gl, data) {
  5477. // Not enough data to contain header ?
  5478. if (data.length < 19) {
  5479. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5480. return;
  5481. }
  5482. // Read Header
  5483. var offset = 18;
  5484. var header = TGATools.GetTGAHeader(data);
  5485. // Assume it's a valid Targa file.
  5486. if (header.id_length + offset > data.length) {
  5487. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5488. return;
  5489. }
  5490. // Skip not needed data
  5491. offset += header.id_length;
  5492. var use_rle = false;
  5493. var use_pal = false;
  5494. var use_rgb = false;
  5495. var use_grey = false;
  5496. // Get some informations.
  5497. switch (header.image_type) {
  5498. case TGATools._TYPE_RLE_INDEXED:
  5499. use_rle = true;
  5500. case TGATools._TYPE_INDEXED:
  5501. use_pal = true;
  5502. break;
  5503. case TGATools._TYPE_RLE_RGB:
  5504. use_rle = true;
  5505. case TGATools._TYPE_RGB:
  5506. use_rgb = true;
  5507. break;
  5508. case TGATools._TYPE_RLE_GREY:
  5509. use_rle = true;
  5510. case TGATools._TYPE_GREY:
  5511. use_grey = true;
  5512. break;
  5513. }
  5514. var pixel_data;
  5515. var numAlphaBits = header.flags & 0xf;
  5516. var pixel_size = header.pixel_size >> 3;
  5517. var pixel_total = header.width * header.height * pixel_size;
  5518. // Read palettes
  5519. var palettes;
  5520. if (use_pal) {
  5521. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5522. }
  5523. // Read LRE
  5524. if (use_rle) {
  5525. pixel_data = new Uint8Array(pixel_total);
  5526. var c, count, i;
  5527. var localOffset = 0;
  5528. var pixels = new Uint8Array(pixel_size);
  5529. while (offset < pixel_total && localOffset < pixel_total) {
  5530. c = data[offset++];
  5531. count = (c & 0x7f) + 1;
  5532. // RLE pixels
  5533. if (c & 0x80) {
  5534. // Bind pixel tmp array
  5535. for (i = 0; i < pixel_size; ++i) {
  5536. pixels[i] = data[offset++];
  5537. }
  5538. // Copy pixel array
  5539. for (i = 0; i < count; ++i) {
  5540. pixel_data.set(pixels, localOffset + i * pixel_size);
  5541. }
  5542. localOffset += pixel_size * count;
  5543. }
  5544. else {
  5545. count *= pixel_size;
  5546. for (i = 0; i < count; ++i) {
  5547. pixel_data[localOffset + i] = data[offset++];
  5548. }
  5549. localOffset += count;
  5550. }
  5551. }
  5552. }
  5553. else {
  5554. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5555. }
  5556. // Load to texture
  5557. var x_start, y_start, x_step, y_step, y_end, x_end;
  5558. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5559. default:
  5560. case TGATools._ORIGIN_UL:
  5561. x_start = 0;
  5562. x_step = 1;
  5563. x_end = header.width;
  5564. y_start = 0;
  5565. y_step = 1;
  5566. y_end = header.height;
  5567. break;
  5568. case TGATools._ORIGIN_BL:
  5569. x_start = 0;
  5570. x_step = 1;
  5571. x_end = header.width;
  5572. y_start = header.height - 1;
  5573. y_step = -1;
  5574. y_end = -1;
  5575. break;
  5576. case TGATools._ORIGIN_UR:
  5577. x_start = header.width - 1;
  5578. x_step = -1;
  5579. x_end = -1;
  5580. y_start = 0;
  5581. y_step = 1;
  5582. y_end = header.height;
  5583. break;
  5584. case TGATools._ORIGIN_BR:
  5585. x_start = header.width - 1;
  5586. x_step = -1;
  5587. x_end = -1;
  5588. y_start = header.height - 1;
  5589. y_step = -1;
  5590. y_end = -1;
  5591. break;
  5592. }
  5593. // Load the specify method
  5594. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5595. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5596. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5597. };
  5598. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5599. var image = pixel_data, colormap = palettes;
  5600. var width = header.width, height = header.height;
  5601. var color, i = 0, x, y;
  5602. var imageData = new Uint8Array(width * height * 4);
  5603. for (y = y_start; y !== y_end; y += y_step) {
  5604. for (x = x_start; x !== x_end; x += x_step, i++) {
  5605. color = image[i];
  5606. imageData[(x + width * y) * 4 + 3] = 255;
  5607. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5608. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5609. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5610. }
  5611. }
  5612. return imageData;
  5613. };
  5614. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5615. var image = pixel_data;
  5616. var width = header.width, height = header.height;
  5617. var color, i = 0, x, y;
  5618. var imageData = new Uint8Array(width * height * 4);
  5619. for (y = y_start; y !== y_end; y += y_step) {
  5620. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5621. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5622. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5623. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5624. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5625. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5626. }
  5627. }
  5628. return imageData;
  5629. };
  5630. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5631. var image = pixel_data;
  5632. var width = header.width, height = header.height;
  5633. var i = 0, x, y;
  5634. var imageData = new Uint8Array(width * height * 4);
  5635. for (y = y_start; y !== y_end; y += y_step) {
  5636. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5637. imageData[(x + width * y) * 4 + 3] = 255;
  5638. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5639. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5640. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5641. }
  5642. }
  5643. return imageData;
  5644. };
  5645. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5646. var image = pixel_data;
  5647. var width = header.width, height = header.height;
  5648. var i = 0, x, y;
  5649. var imageData = new Uint8Array(width * height * 4);
  5650. for (y = y_start; y !== y_end; y += y_step) {
  5651. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5652. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5653. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5654. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5655. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5656. }
  5657. }
  5658. return imageData;
  5659. };
  5660. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5661. var image = pixel_data;
  5662. var width = header.width, height = header.height;
  5663. var color, i = 0, x, y;
  5664. var imageData = new Uint8Array(width * height * 4);
  5665. for (y = y_start; y !== y_end; y += y_step) {
  5666. for (x = x_start; x !== x_end; x += x_step, i++) {
  5667. color = image[i];
  5668. imageData[(x + width * y) * 4 + 0] = color;
  5669. imageData[(x + width * y) * 4 + 1] = color;
  5670. imageData[(x + width * y) * 4 + 2] = color;
  5671. imageData[(x + width * y) * 4 + 3] = 255;
  5672. }
  5673. }
  5674. return imageData;
  5675. };
  5676. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5677. var image = pixel_data;
  5678. var width = header.width, height = header.height;
  5679. var i = 0, x, y;
  5680. var imageData = new Uint8Array(width * height * 4);
  5681. for (y = y_start; y !== y_end; y += y_step) {
  5682. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5683. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5684. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5685. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5686. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5687. }
  5688. }
  5689. return imageData;
  5690. };
  5691. return TGATools;
  5692. }());
  5693. TGATools._TYPE_NO_DATA = 0;
  5694. TGATools._TYPE_INDEXED = 1;
  5695. TGATools._TYPE_RGB = 2;
  5696. TGATools._TYPE_GREY = 3;
  5697. TGATools._TYPE_RLE_INDEXED = 9;
  5698. TGATools._TYPE_RLE_RGB = 10;
  5699. TGATools._TYPE_RLE_GREY = 11;
  5700. TGATools._ORIGIN_MASK = 0x30;
  5701. TGATools._ORIGIN_SHIFT = 0x04;
  5702. TGATools._ORIGIN_BL = 0x00;
  5703. TGATools._ORIGIN_BR = 0x01;
  5704. TGATools._ORIGIN_UL = 0x02;
  5705. TGATools._ORIGIN_UR = 0x03;
  5706. Internals.TGATools = TGATools;
  5707. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5708. })(BABYLON || (BABYLON = {}));
  5709. //# sourceMappingURL=babylon.tools.tga.js.map
  5710. var BABYLON;
  5711. (function (BABYLON) {
  5712. var SmartArray = (function () {
  5713. function SmartArray(capacity) {
  5714. this.length = 0;
  5715. this._duplicateId = 0;
  5716. this.data = new Array(capacity);
  5717. this._id = SmartArray._GlobalId++;
  5718. }
  5719. SmartArray.prototype.push = function (value) {
  5720. this.data[this.length++] = value;
  5721. if (this.length > this.data.length) {
  5722. this.data.length *= 2;
  5723. }
  5724. if (!value.__smartArrayFlags) {
  5725. value.__smartArrayFlags = {};
  5726. }
  5727. value.__smartArrayFlags[this._id] = this._duplicateId;
  5728. };
  5729. SmartArray.prototype.forEach = function (func) {
  5730. for (var index = 0; index < this.length; index++) {
  5731. func(this.data[index]);
  5732. }
  5733. };
  5734. SmartArray.prototype.pushNoDuplicate = function (value) {
  5735. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5736. return false;
  5737. }
  5738. this.push(value);
  5739. return true;
  5740. };
  5741. SmartArray.prototype.sort = function (compareFn) {
  5742. this.data.sort(compareFn);
  5743. };
  5744. SmartArray.prototype.reset = function () {
  5745. this.length = 0;
  5746. this._duplicateId++;
  5747. };
  5748. SmartArray.prototype.concat = function (array) {
  5749. if (array.length === 0) {
  5750. return;
  5751. }
  5752. if (this.length + array.length > this.data.length) {
  5753. this.data.length = (this.length + array.length) * 2;
  5754. }
  5755. for (var index = 0; index < array.length; index++) {
  5756. this.data[this.length++] = (array.data || array)[index];
  5757. }
  5758. };
  5759. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5760. if (array.length === 0) {
  5761. return;
  5762. }
  5763. if (this.length + array.length > this.data.length) {
  5764. this.data.length = (this.length + array.length) * 2;
  5765. }
  5766. for (var index = 0; index < array.length; index++) {
  5767. var item = (array.data || array)[index];
  5768. this.pushNoDuplicate(item);
  5769. }
  5770. };
  5771. SmartArray.prototype.indexOf = function (value) {
  5772. var position = this.data.indexOf(value);
  5773. if (position >= this.length) {
  5774. return -1;
  5775. }
  5776. return position;
  5777. };
  5778. return SmartArray;
  5779. }());
  5780. // Statics
  5781. SmartArray._GlobalId = 0;
  5782. BABYLON.SmartArray = SmartArray;
  5783. })(BABYLON || (BABYLON = {}));
  5784. //# sourceMappingURL=babylon.smartArray.js.map
  5785. var BABYLON;
  5786. (function (BABYLON) {
  5787. /**
  5788. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5789. * The underlying implementation relies on an associative array to ensure the best performances.
  5790. * The value can be anything including 'null' but except 'undefined'
  5791. */
  5792. var StringDictionary = (function () {
  5793. function StringDictionary() {
  5794. this._count = 0;
  5795. this._data = {};
  5796. }
  5797. /**
  5798. * This will clear this dictionary and copy the content from the 'source' one.
  5799. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5800. * @param source the dictionary to take the content from and copy to this dictionary
  5801. */
  5802. StringDictionary.prototype.copyFrom = function (source) {
  5803. var _this = this;
  5804. this.clear();
  5805. source.forEach(function (t, v) { return _this.add(t, v); });
  5806. };
  5807. /**
  5808. * Get a value based from its key
  5809. * @param key the given key to get the matching value from
  5810. * @return the value if found, otherwise undefined is returned
  5811. */
  5812. StringDictionary.prototype.get = function (key) {
  5813. var val = this._data[key];
  5814. if (val !== undefined) {
  5815. return val;
  5816. }
  5817. return undefined;
  5818. };
  5819. /**
  5820. * Get a value from its key or add it if it doesn't exist.
  5821. * This method will ensure you that a given key/data will be present in the dictionary.
  5822. * @param key the given key to get the matching value from
  5823. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5824. * The factory will only be invoked if there's no data for the given key.
  5825. * @return the value corresponding to the key.
  5826. */
  5827. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5828. var val = this.get(key);
  5829. if (val !== undefined) {
  5830. return val;
  5831. }
  5832. val = factory(key);
  5833. if (val) {
  5834. this.add(key, val);
  5835. }
  5836. return val;
  5837. };
  5838. /**
  5839. * Get a value from its key if present in the dictionary otherwise add it
  5840. * @param key the key to get the value from
  5841. * @param val if there's no such key/value pair in the dictionary add it with this value
  5842. * @return the value corresponding to the key
  5843. */
  5844. StringDictionary.prototype.getOrAdd = function (key, val) {
  5845. var curVal = this.get(key);
  5846. if (curVal !== undefined) {
  5847. return curVal;
  5848. }
  5849. this.add(key, val);
  5850. return val;
  5851. };
  5852. /**
  5853. * Check if there's a given key in the dictionary
  5854. * @param key the key to check for
  5855. * @return true if the key is present, false otherwise
  5856. */
  5857. StringDictionary.prototype.contains = function (key) {
  5858. return this._data[key] !== undefined;
  5859. };
  5860. /**
  5861. * Add a new key and its corresponding value
  5862. * @param key the key to add
  5863. * @param value the value corresponding to the key
  5864. * @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
  5865. */
  5866. StringDictionary.prototype.add = function (key, value) {
  5867. if (this._data[key] !== undefined) {
  5868. return false;
  5869. }
  5870. this._data[key] = value;
  5871. ++this._count;
  5872. return true;
  5873. };
  5874. StringDictionary.prototype.set = function (key, value) {
  5875. if (this._data[key] === undefined) {
  5876. return false;
  5877. }
  5878. this._data[key] = value;
  5879. return true;
  5880. };
  5881. /**
  5882. * Get the element of the given key and remove it from the dictionary
  5883. * @param key
  5884. */
  5885. StringDictionary.prototype.getAndRemove = function (key) {
  5886. var val = this.get(key);
  5887. if (val !== undefined) {
  5888. delete this._data[key];
  5889. --this._count;
  5890. return val;
  5891. }
  5892. return null;
  5893. };
  5894. /**
  5895. * Remove a key/value from the dictionary.
  5896. * @param key the key to remove
  5897. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5898. */
  5899. StringDictionary.prototype.remove = function (key) {
  5900. if (this.contains(key)) {
  5901. delete this._data[key];
  5902. --this._count;
  5903. return true;
  5904. }
  5905. return false;
  5906. };
  5907. /**
  5908. * Clear the whole content of the dictionary
  5909. */
  5910. StringDictionary.prototype.clear = function () {
  5911. this._data = {};
  5912. this._count = 0;
  5913. };
  5914. Object.defineProperty(StringDictionary.prototype, "count", {
  5915. get: function () {
  5916. return this._count;
  5917. },
  5918. enumerable: true,
  5919. configurable: true
  5920. });
  5921. /**
  5922. * Execute a callback on each key/val of the dictionary.
  5923. * Note that you can remove any element in this dictionary in the callback implementation
  5924. * @param callback the callback to execute on a given key/value pair
  5925. */
  5926. StringDictionary.prototype.forEach = function (callback) {
  5927. for (var cur in this._data) {
  5928. var val = this._data[cur];
  5929. callback(cur, val);
  5930. }
  5931. };
  5932. /**
  5933. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5934. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5935. * Note that you can remove any element in this dictionary in the callback implementation
  5936. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5937. */
  5938. StringDictionary.prototype.first = function (callback) {
  5939. for (var cur in this._data) {
  5940. var val = this._data[cur];
  5941. var res = callback(cur, val);
  5942. if (res) {
  5943. return res;
  5944. }
  5945. }
  5946. return null;
  5947. };
  5948. return StringDictionary;
  5949. }());
  5950. BABYLON.StringDictionary = StringDictionary;
  5951. })(BABYLON || (BABYLON = {}));
  5952. //# sourceMappingURL=babylon.stringDictionary.js.map
  5953. var BABYLON;
  5954. (function (BABYLON) {
  5955. // Screenshots
  5956. var screenshotCanvas;
  5957. var cloneValue = function (source, destinationObject) {
  5958. if (!source)
  5959. return null;
  5960. if (source instanceof BABYLON.Mesh) {
  5961. return null;
  5962. }
  5963. if (source instanceof BABYLON.SubMesh) {
  5964. return source.clone(destinationObject);
  5965. }
  5966. else if (source.clone) {
  5967. return source.clone();
  5968. }
  5969. return null;
  5970. };
  5971. var Tools = (function () {
  5972. function Tools() {
  5973. }
  5974. ;
  5975. Tools.Instantiate = function (className) {
  5976. var arr = className.split(".");
  5977. var fn = (window || this);
  5978. for (var i = 0, len = arr.length; i < len; i++) {
  5979. fn = fn[arr[i]];
  5980. }
  5981. if (typeof fn !== "function") {
  5982. return null;
  5983. }
  5984. return fn;
  5985. };
  5986. Tools.SetImmediate = function (action) {
  5987. if (window.setImmediate) {
  5988. window.setImmediate(action);
  5989. }
  5990. else {
  5991. setTimeout(action, 1);
  5992. }
  5993. };
  5994. Tools.IsExponentOfTwo = function (value) {
  5995. var count = 1;
  5996. do {
  5997. count *= 2;
  5998. } while (count < value);
  5999. return count === value;
  6000. };
  6001. Tools.GetExponentOfTwo = function (value, max) {
  6002. var count = 1;
  6003. do {
  6004. count *= 2;
  6005. } while (count < value);
  6006. if (count > max)
  6007. count = max;
  6008. return count;
  6009. };
  6010. Tools.GetFilename = function (path) {
  6011. var index = path.lastIndexOf("/");
  6012. if (index < 0)
  6013. return path;
  6014. return path.substring(index + 1);
  6015. };
  6016. Tools.GetDOMTextContent = function (element) {
  6017. var result = "";
  6018. var child = element.firstChild;
  6019. while (child) {
  6020. if (child.nodeType === 3) {
  6021. result += child.textContent;
  6022. }
  6023. child = child.nextSibling;
  6024. }
  6025. return result;
  6026. };
  6027. Tools.ToDegrees = function (angle) {
  6028. return angle * 180 / Math.PI;
  6029. };
  6030. Tools.ToRadians = function (angle) {
  6031. return angle * Math.PI / 180;
  6032. };
  6033. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6034. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6035. var output = "";
  6036. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6037. var i = 0;
  6038. var bytes = new Uint8Array(buffer);
  6039. while (i < bytes.length) {
  6040. chr1 = bytes[i++];
  6041. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6042. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6043. enc1 = chr1 >> 2;
  6044. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6045. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6046. enc4 = chr3 & 63;
  6047. if (isNaN(chr2)) {
  6048. enc3 = enc4 = 64;
  6049. }
  6050. else if (isNaN(chr3)) {
  6051. enc4 = 64;
  6052. }
  6053. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6054. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6055. }
  6056. return "data:image/png;base64," + output;
  6057. };
  6058. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6059. if (bias === void 0) { bias = null; }
  6060. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6061. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6062. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6063. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6064. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6065. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6066. }
  6067. if (bias) {
  6068. minimum.x -= minimum.x * bias.x + bias.y;
  6069. minimum.y -= minimum.y * bias.x + bias.y;
  6070. minimum.z -= minimum.z * bias.x + bias.y;
  6071. maximum.x += maximum.x * bias.x + bias.y;
  6072. maximum.y += maximum.y * bias.x + bias.y;
  6073. maximum.z += maximum.z * bias.x + bias.y;
  6074. }
  6075. return {
  6076. minimum: minimum,
  6077. maximum: maximum
  6078. };
  6079. };
  6080. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6081. if (bias === void 0) { bias = null; }
  6082. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6083. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6084. if (!stride) {
  6085. stride = 3;
  6086. }
  6087. for (var index = start; index < start + count; index++) {
  6088. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6089. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6090. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6091. }
  6092. if (bias) {
  6093. minimum.x -= minimum.x * bias.x + bias.y;
  6094. minimum.y -= minimum.y * bias.x + bias.y;
  6095. minimum.z -= minimum.z * bias.x + bias.y;
  6096. maximum.x += maximum.x * bias.x + bias.y;
  6097. maximum.y += maximum.y * bias.x + bias.y;
  6098. maximum.z += maximum.z * bias.x + bias.y;
  6099. }
  6100. return {
  6101. minimum: minimum,
  6102. maximum: maximum
  6103. };
  6104. };
  6105. Tools.Vector2ArrayFeeder = function (array) {
  6106. return function (index) {
  6107. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6108. var length = isFloatArray ? array.length / 2 : array.length;
  6109. if (index >= length) {
  6110. return null;
  6111. }
  6112. if (isFloatArray) {
  6113. var fa = array;
  6114. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6115. }
  6116. var a = array;
  6117. return a[index];
  6118. };
  6119. };
  6120. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6121. if (bias === void 0) { bias = null; }
  6122. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6123. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6124. var i = 0;
  6125. var cur = feeder(i++);
  6126. while (cur) {
  6127. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6128. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6129. cur = feeder(i++);
  6130. }
  6131. if (bias) {
  6132. minimum.x -= minimum.x * bias.x + bias.y;
  6133. minimum.y -= minimum.y * bias.x + bias.y;
  6134. maximum.x += maximum.x * bias.x + bias.y;
  6135. maximum.y += maximum.y * bias.x + bias.y;
  6136. }
  6137. return {
  6138. minimum: minimum,
  6139. maximum: maximum
  6140. };
  6141. };
  6142. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6143. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6144. return undefined;
  6145. return Array.isArray(obj) ? obj : [obj];
  6146. };
  6147. // Misc.
  6148. Tools.GetPointerPrefix = function () {
  6149. var eventPrefix = "pointer";
  6150. // Check if pointer events are supported
  6151. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6152. eventPrefix = "mouse";
  6153. }
  6154. return eventPrefix;
  6155. };
  6156. /**
  6157. * @param func - the function to be called
  6158. * @param requester - the object that will request the next frame. Falls back to window.
  6159. */
  6160. Tools.QueueNewFrame = function (func, requester) {
  6161. if (requester === void 0) { requester = window; }
  6162. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6163. /*if(requester.isPresenting) {
  6164. return;
  6165. } else*/ if (requester.requestAnimationFrame)
  6166. requester.requestAnimationFrame(func);
  6167. else if (requester.msRequestAnimationFrame)
  6168. requester.msRequestAnimationFrame(func);
  6169. else if (requester.webkitRequestAnimationFrame)
  6170. requester.webkitRequestAnimationFrame(func);
  6171. else if (requester.mozRequestAnimationFrame)
  6172. requester.mozRequestAnimationFrame(func);
  6173. else if (requester.oRequestAnimationFrame)
  6174. requester.oRequestAnimationFrame(func);
  6175. else {
  6176. window.setTimeout(func, 16);
  6177. }
  6178. };
  6179. Tools.RequestFullscreen = function (element) {
  6180. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6181. if (!requestFunction)
  6182. return;
  6183. requestFunction.call(element);
  6184. };
  6185. Tools.ExitFullscreen = function () {
  6186. if (document.exitFullscreen) {
  6187. document.exitFullscreen();
  6188. }
  6189. else if (document.mozCancelFullScreen) {
  6190. document.mozCancelFullScreen();
  6191. }
  6192. else if (document.webkitCancelFullScreen) {
  6193. document.webkitCancelFullScreen();
  6194. }
  6195. else if (document.msCancelFullScreen) {
  6196. document.msCancelFullScreen();
  6197. }
  6198. };
  6199. Tools.SetCorsBehavior = function (url, img) {
  6200. if (Tools.CorsBehavior) {
  6201. switch (typeof (Tools.CorsBehavior)) {
  6202. case "function":
  6203. var result = Tools.CorsBehavior(url);
  6204. if (result) {
  6205. img.crossOrigin = result;
  6206. }
  6207. break;
  6208. case "string":
  6209. default:
  6210. img.crossOrigin = Tools.CorsBehavior;
  6211. break;
  6212. }
  6213. }
  6214. };
  6215. // External files
  6216. Tools.CleanUrl = function (url) {
  6217. url = url.replace(/#/mg, "%23");
  6218. return url;
  6219. };
  6220. Tools.LoadImage = function (url, onload, onerror, database) {
  6221. if (url instanceof ArrayBuffer) {
  6222. url = Tools.EncodeArrayBufferTobase64(url);
  6223. }
  6224. url = Tools.CleanUrl(url);
  6225. var img = new Image();
  6226. if (url.substr(0, 5) !== "data:") {
  6227. Tools.SetCorsBehavior(url, img);
  6228. }
  6229. img.onload = function () {
  6230. onload(img);
  6231. };
  6232. img.onerror = function (err) {
  6233. Tools.Error("Error while trying to load image: " + url);
  6234. if (Tools.UseFallbackTexture) {
  6235. img.src = Tools.fallbackTexture;
  6236. onload(img);
  6237. }
  6238. else {
  6239. onerror();
  6240. }
  6241. };
  6242. var noIndexedDB = function () {
  6243. img.src = url;
  6244. };
  6245. var loadFromIndexedDB = function () {
  6246. database.loadImageFromDB(url, img);
  6247. };
  6248. //ANY database to do!
  6249. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6250. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6251. }
  6252. else {
  6253. if (url.indexOf("file:") === -1) {
  6254. noIndexedDB();
  6255. }
  6256. else {
  6257. var textureName = url.substring(5).toLowerCase();
  6258. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6259. try {
  6260. var blobURL;
  6261. try {
  6262. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6263. }
  6264. catch (ex) {
  6265. // Chrome doesn't support oneTimeOnly parameter
  6266. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6267. }
  6268. img.src = blobURL;
  6269. }
  6270. catch (e) {
  6271. img.src = null;
  6272. }
  6273. }
  6274. else {
  6275. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6276. img.src = Tools.fallbackTexture;
  6277. }
  6278. }
  6279. }
  6280. return img;
  6281. };
  6282. //ANY
  6283. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6284. url = Tools.CleanUrl(url);
  6285. var noIndexedDB = function () {
  6286. var request = new XMLHttpRequest();
  6287. var loadUrl = Tools.BaseUrl + url;
  6288. request.open('GET', loadUrl, true);
  6289. if (useArrayBuffer) {
  6290. request.responseType = "arraybuffer";
  6291. }
  6292. request.onprogress = progressCallBack;
  6293. request.onreadystatechange = function () {
  6294. if (request.readyState === 4) {
  6295. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6296. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6297. callback(!useArrayBuffer ? request.responseText : request.response);
  6298. }
  6299. else {
  6300. if (onError) {
  6301. onError();
  6302. }
  6303. else {
  6304. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6305. }
  6306. }
  6307. }
  6308. };
  6309. request.send(null);
  6310. };
  6311. var loadFromIndexedDB = function () {
  6312. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6313. };
  6314. if (url.indexOf("file:") !== -1) {
  6315. var fileName = url.substring(5).toLowerCase();
  6316. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6317. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6318. }
  6319. else {
  6320. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6321. }
  6322. }
  6323. else {
  6324. // Caching all files
  6325. if (database && database.enableSceneOffline) {
  6326. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6327. }
  6328. else {
  6329. noIndexedDB();
  6330. }
  6331. }
  6332. };
  6333. /**
  6334. * Load a script (identified by an url). When the url returns, the
  6335. * content of this file is added into a new script element, attached to the DOM (body element)
  6336. */
  6337. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6338. var head = document.getElementsByTagName('head')[0];
  6339. var script = document.createElement('script');
  6340. script.type = 'text/javascript';
  6341. script.src = scriptUrl;
  6342. var self = this;
  6343. script.onload = function () {
  6344. if (onSuccess) {
  6345. onSuccess();
  6346. }
  6347. };
  6348. script.onerror = function () {
  6349. if (onError) {
  6350. onError();
  6351. }
  6352. };
  6353. head.appendChild(script);
  6354. };
  6355. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6356. var reader = new FileReader();
  6357. reader.onload = function (e) {
  6358. //target doesn't have result from ts 1.3
  6359. callback(e.target['result']);
  6360. };
  6361. reader.onprogress = progressCallback;
  6362. reader.readAsDataURL(fileToLoad);
  6363. };
  6364. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6365. var reader = new FileReader();
  6366. reader.onerror = function (e) {
  6367. Tools.Log("Error while reading file: " + fileToLoad.name);
  6368. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6369. };
  6370. reader.onload = function (e) {
  6371. //target doesn't have result from ts 1.3
  6372. callback(e.target['result']);
  6373. };
  6374. reader.onprogress = progressCallBack;
  6375. if (!useArrayBuffer) {
  6376. // Asynchronous read
  6377. reader.readAsText(fileToLoad);
  6378. }
  6379. else {
  6380. reader.readAsArrayBuffer(fileToLoad);
  6381. }
  6382. };
  6383. //returns a downloadable url to a file content.
  6384. Tools.FileAsURL = function (content) {
  6385. var fileBlob = new Blob([content]);
  6386. var url = window.URL || window.webkitURL;
  6387. var link = url.createObjectURL(fileBlob);
  6388. return link;
  6389. };
  6390. // Misc.
  6391. Tools.Format = function (value, decimals) {
  6392. if (decimals === void 0) { decimals = 2; }
  6393. return value.toFixed(decimals);
  6394. };
  6395. Tools.CheckExtends = function (v, min, max) {
  6396. if (v.x < min.x)
  6397. min.x = v.x;
  6398. if (v.y < min.y)
  6399. min.y = v.y;
  6400. if (v.z < min.z)
  6401. min.z = v.z;
  6402. if (v.x > max.x)
  6403. max.x = v.x;
  6404. if (v.y > max.y)
  6405. max.y = v.y;
  6406. if (v.z > max.z)
  6407. max.z = v.z;
  6408. };
  6409. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6410. for (var prop in source) {
  6411. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6412. continue;
  6413. }
  6414. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6415. continue;
  6416. }
  6417. var sourceValue = source[prop];
  6418. var typeOfSourceValue = typeof sourceValue;
  6419. if (typeOfSourceValue === "function") {
  6420. continue;
  6421. }
  6422. if (typeOfSourceValue === "object") {
  6423. if (sourceValue instanceof Array) {
  6424. destination[prop] = [];
  6425. if (sourceValue.length > 0) {
  6426. if (typeof sourceValue[0] == "object") {
  6427. for (var index = 0; index < sourceValue.length; index++) {
  6428. var clonedValue = cloneValue(sourceValue[index], destination);
  6429. if (destination[prop].indexOf(clonedValue) === -1) {
  6430. destination[prop].push(clonedValue);
  6431. }
  6432. }
  6433. }
  6434. else {
  6435. destination[prop] = sourceValue.slice(0);
  6436. }
  6437. }
  6438. }
  6439. else {
  6440. destination[prop] = cloneValue(sourceValue, destination);
  6441. }
  6442. }
  6443. else {
  6444. destination[prop] = sourceValue;
  6445. }
  6446. }
  6447. };
  6448. Tools.IsEmpty = function (obj) {
  6449. for (var i in obj) {
  6450. return false;
  6451. }
  6452. return true;
  6453. };
  6454. Tools.RegisterTopRootEvents = function (events) {
  6455. for (var index = 0; index < events.length; index++) {
  6456. var event = events[index];
  6457. window.addEventListener(event.name, event.handler, false);
  6458. try {
  6459. if (window.parent) {
  6460. window.parent.addEventListener(event.name, event.handler, false);
  6461. }
  6462. }
  6463. catch (e) {
  6464. }
  6465. }
  6466. };
  6467. Tools.UnregisterTopRootEvents = function (events) {
  6468. for (var index = 0; index < events.length; index++) {
  6469. var event = events[index];
  6470. window.removeEventListener(event.name, event.handler);
  6471. try {
  6472. if (window.parent) {
  6473. window.parent.removeEventListener(event.name, event.handler);
  6474. }
  6475. }
  6476. catch (e) {
  6477. }
  6478. }
  6479. };
  6480. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6481. if (mimeType === void 0) { mimeType = "image/png"; }
  6482. // Read the contents of the framebuffer
  6483. var numberOfChannelsByLine = width * 4;
  6484. var halfHeight = height / 2;
  6485. //Reading datas from WebGL
  6486. var data = engine.readPixels(0, 0, width, height);
  6487. //To flip image on Y axis.
  6488. for (var i = 0; i < halfHeight; i++) {
  6489. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6490. var currentCell = j + i * numberOfChannelsByLine;
  6491. var targetLine = height - i - 1;
  6492. var targetCell = j + targetLine * numberOfChannelsByLine;
  6493. var temp = data[currentCell];
  6494. data[currentCell] = data[targetCell];
  6495. data[targetCell] = temp;
  6496. }
  6497. }
  6498. // Create a 2D canvas to store the result
  6499. if (!screenshotCanvas) {
  6500. screenshotCanvas = document.createElement('canvas');
  6501. }
  6502. screenshotCanvas.width = width;
  6503. screenshotCanvas.height = height;
  6504. var context = screenshotCanvas.getContext('2d');
  6505. // Copy the pixels to a 2D canvas
  6506. var imageData = context.createImageData(width, height);
  6507. var castData = (imageData.data);
  6508. castData.set(data);
  6509. context.putImageData(imageData, 0, 0);
  6510. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6511. };
  6512. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6513. if (mimeType === void 0) { mimeType = "image/png"; }
  6514. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6515. if (successCallback) {
  6516. successCallback(base64Image);
  6517. }
  6518. else {
  6519. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6520. if (("download" in document.createElement("a"))) {
  6521. var a = window.document.createElement("a");
  6522. a.href = base64Image;
  6523. var date = new Date();
  6524. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6525. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6526. window.document.body.appendChild(a);
  6527. a.addEventListener("click", function () {
  6528. a.parentElement.removeChild(a);
  6529. });
  6530. a.click();
  6531. }
  6532. else {
  6533. var newWindow = window.open("");
  6534. var img = newWindow.document.createElement("img");
  6535. img.src = base64Image;
  6536. newWindow.document.body.appendChild(img);
  6537. }
  6538. }
  6539. };
  6540. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6541. if (mimeType === void 0) { mimeType = "image/png"; }
  6542. var width;
  6543. var height;
  6544. // If a precision value is specified
  6545. if (size.precision) {
  6546. width = Math.round(engine.getRenderWidth() * size.precision);
  6547. height = Math.round(width / engine.getAspectRatio(camera));
  6548. }
  6549. else if (size.width && size.height) {
  6550. width = size.width;
  6551. height = size.height;
  6552. }
  6553. else if (size.width && !size.height) {
  6554. width = size.width;
  6555. height = Math.round(width / engine.getAspectRatio(camera));
  6556. }
  6557. else if (size.height && !size.width) {
  6558. height = size.height;
  6559. width = Math.round(height * engine.getAspectRatio(camera));
  6560. }
  6561. else if (!isNaN(size)) {
  6562. height = size;
  6563. width = size;
  6564. }
  6565. else {
  6566. Tools.Error("Invalid 'size' parameter !");
  6567. return;
  6568. }
  6569. if (!screenshotCanvas) {
  6570. screenshotCanvas = document.createElement('canvas');
  6571. }
  6572. screenshotCanvas.width = width;
  6573. screenshotCanvas.height = height;
  6574. var renderContext = screenshotCanvas.getContext("2d");
  6575. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6576. var newWidth = width;
  6577. var newHeight = newWidth / ratio;
  6578. if (newHeight > height) {
  6579. newHeight = height;
  6580. newWidth = newHeight * ratio;
  6581. }
  6582. var offsetX = Math.max(0, width - newWidth) / 2;
  6583. var offsetY = Math.max(0, height - newHeight) / 2;
  6584. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6585. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6586. };
  6587. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  6588. if (mimeType === void 0) { mimeType = "image/png"; }
  6589. var width;
  6590. var height;
  6591. //If a precision value is specified
  6592. if (size.precision) {
  6593. width = Math.round(engine.getRenderWidth() * size.precision);
  6594. height = Math.round(width / engine.getAspectRatio(camera));
  6595. size = { width: width, height: height };
  6596. }
  6597. else if (size.width && size.height) {
  6598. width = size.width;
  6599. height = size.height;
  6600. }
  6601. else if (size.width && !size.height) {
  6602. width = size.width;
  6603. height = Math.round(width / engine.getAspectRatio(camera));
  6604. size = { width: width, height: height };
  6605. }
  6606. else if (size.height && !size.width) {
  6607. height = size.height;
  6608. width = Math.round(height * engine.getAspectRatio(camera));
  6609. size = { width: width, height: height };
  6610. }
  6611. else if (!isNaN(size)) {
  6612. height = size;
  6613. width = size;
  6614. }
  6615. else {
  6616. Tools.Error("Invalid 'size' parameter !");
  6617. return;
  6618. }
  6619. var scene = camera.getScene();
  6620. var previousCamera = null;
  6621. if (scene.activeCamera !== camera) {
  6622. previousCamera = scene.activeCamera;
  6623. scene.activeCamera = camera;
  6624. }
  6625. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6626. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6627. texture.renderList = scene.meshes;
  6628. texture.onAfterRenderObservable.add(function () {
  6629. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6630. });
  6631. scene.incrementRenderId();
  6632. scene.resetCachedMaterial();
  6633. texture.render(true);
  6634. texture.dispose();
  6635. if (previousCamera) {
  6636. scene.activeCamera = previousCamera;
  6637. }
  6638. camera.getProjectionMatrix(true); // Force cache refresh;
  6639. };
  6640. // XHR response validator for local file scenario
  6641. Tools.ValidateXHRData = function (xhr, dataType) {
  6642. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6643. if (dataType === void 0) { dataType = 7; }
  6644. try {
  6645. if (dataType & 1) {
  6646. if (xhr.responseText && xhr.responseText.length > 0) {
  6647. return true;
  6648. }
  6649. else if (dataType === 1) {
  6650. return false;
  6651. }
  6652. }
  6653. if (dataType & 2) {
  6654. // Check header width and height since there is no "TGA" magic number
  6655. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6656. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6657. return true;
  6658. }
  6659. else if (dataType === 2) {
  6660. return false;
  6661. }
  6662. }
  6663. if (dataType & 4) {
  6664. // Check for the "DDS" magic number
  6665. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6666. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6667. return true;
  6668. }
  6669. else {
  6670. return false;
  6671. }
  6672. }
  6673. }
  6674. catch (e) {
  6675. }
  6676. return false;
  6677. };
  6678. /**
  6679. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6680. * Be aware Math.random() could cause collisions, but:
  6681. * "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"
  6682. */
  6683. Tools.RandomId = function () {
  6684. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6685. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6686. return v.toString(16);
  6687. });
  6688. };
  6689. Object.defineProperty(Tools, "NoneLogLevel", {
  6690. get: function () {
  6691. return Tools._NoneLogLevel;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Tools, "MessageLogLevel", {
  6697. get: function () {
  6698. return Tools._MessageLogLevel;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Object.defineProperty(Tools, "WarningLogLevel", {
  6704. get: function () {
  6705. return Tools._WarningLogLevel;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Object.defineProperty(Tools, "ErrorLogLevel", {
  6711. get: function () {
  6712. return Tools._ErrorLogLevel;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(Tools, "AllLogLevel", {
  6718. get: function () {
  6719. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Tools._AddLogEntry = function (entry) {
  6725. Tools._LogCache = entry + Tools._LogCache;
  6726. if (Tools.OnNewCacheEntry) {
  6727. Tools.OnNewCacheEntry(entry);
  6728. }
  6729. };
  6730. Tools._FormatMessage = function (message) {
  6731. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6732. var date = new Date();
  6733. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6734. };
  6735. Tools._LogDisabled = function (message) {
  6736. // nothing to do
  6737. };
  6738. Tools._LogEnabled = function (message) {
  6739. var formattedMessage = Tools._FormatMessage(message);
  6740. console.log("BJS - " + formattedMessage);
  6741. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6742. Tools._AddLogEntry(entry);
  6743. };
  6744. Tools._WarnDisabled = function (message) {
  6745. // nothing to do
  6746. };
  6747. Tools._WarnEnabled = function (message) {
  6748. var formattedMessage = Tools._FormatMessage(message);
  6749. console.warn("BJS - " + formattedMessage);
  6750. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6751. Tools._AddLogEntry(entry);
  6752. };
  6753. Tools._ErrorDisabled = function (message) {
  6754. // nothing to do
  6755. };
  6756. Tools._ErrorEnabled = function (message) {
  6757. Tools.errorsCount++;
  6758. var formattedMessage = Tools._FormatMessage(message);
  6759. console.error("BJS - " + formattedMessage);
  6760. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6761. Tools._AddLogEntry(entry);
  6762. };
  6763. Object.defineProperty(Tools, "LogCache", {
  6764. get: function () {
  6765. return Tools._LogCache;
  6766. },
  6767. enumerable: true,
  6768. configurable: true
  6769. });
  6770. Tools.ClearLogCache = function () {
  6771. Tools._LogCache = "";
  6772. Tools.errorsCount = 0;
  6773. };
  6774. Object.defineProperty(Tools, "LogLevels", {
  6775. set: function (level) {
  6776. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6777. Tools.Log = Tools._LogEnabled;
  6778. }
  6779. else {
  6780. Tools.Log = Tools._LogDisabled;
  6781. }
  6782. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6783. Tools.Warn = Tools._WarnEnabled;
  6784. }
  6785. else {
  6786. Tools.Warn = Tools._WarnDisabled;
  6787. }
  6788. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6789. Tools.Error = Tools._ErrorEnabled;
  6790. }
  6791. else {
  6792. Tools.Error = Tools._ErrorDisabled;
  6793. }
  6794. },
  6795. enumerable: true,
  6796. configurable: true
  6797. });
  6798. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6799. get: function () {
  6800. return Tools._PerformanceNoneLogLevel;
  6801. },
  6802. enumerable: true,
  6803. configurable: true
  6804. });
  6805. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6806. get: function () {
  6807. return Tools._PerformanceUserMarkLogLevel;
  6808. },
  6809. enumerable: true,
  6810. configurable: true
  6811. });
  6812. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6813. get: function () {
  6814. return Tools._PerformanceConsoleLogLevel;
  6815. },
  6816. enumerable: true,
  6817. configurable: true
  6818. });
  6819. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6820. set: function (level) {
  6821. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6822. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6823. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6824. return;
  6825. }
  6826. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6827. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6828. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6829. return;
  6830. }
  6831. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6832. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6833. },
  6834. enumerable: true,
  6835. configurable: true
  6836. });
  6837. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6838. };
  6839. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6840. };
  6841. Tools._StartUserMark = function (counterName, condition) {
  6842. if (condition === void 0) { condition = true; }
  6843. if (!condition || !Tools._performance.mark) {
  6844. return;
  6845. }
  6846. Tools._performance.mark(counterName + "-Begin");
  6847. };
  6848. Tools._EndUserMark = function (counterName, condition) {
  6849. if (condition === void 0) { condition = true; }
  6850. if (!condition || !Tools._performance.mark) {
  6851. return;
  6852. }
  6853. Tools._performance.mark(counterName + "-End");
  6854. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6855. };
  6856. Tools._StartPerformanceConsole = function (counterName, condition) {
  6857. if (condition === void 0) { condition = true; }
  6858. if (!condition) {
  6859. return;
  6860. }
  6861. Tools._StartUserMark(counterName, condition);
  6862. if (console.time) {
  6863. console.time(counterName);
  6864. }
  6865. };
  6866. Tools._EndPerformanceConsole = function (counterName, condition) {
  6867. if (condition === void 0) { condition = true; }
  6868. if (!condition) {
  6869. return;
  6870. }
  6871. Tools._EndUserMark(counterName, condition);
  6872. if (console.time) {
  6873. console.timeEnd(counterName);
  6874. }
  6875. };
  6876. Object.defineProperty(Tools, "Now", {
  6877. get: function () {
  6878. if (window.performance && window.performance.now) {
  6879. return window.performance.now();
  6880. }
  6881. return new Date().getTime();
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. /**
  6887. * This method will return the name of the class used to create the instance of the given object.
  6888. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6889. * @param object the object to get the class name from
  6890. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6891. */
  6892. Tools.getClassName = function (object, isType) {
  6893. if (isType === void 0) { isType = false; }
  6894. var name = null;
  6895. if (!isType && object.getClassName) {
  6896. name = object.getClassName();
  6897. }
  6898. else {
  6899. if (object instanceof Object) {
  6900. var classObj = isType ? object : Object.getPrototypeOf(object);
  6901. name = classObj.constructor["__bjsclassName__"];
  6902. }
  6903. if (!name) {
  6904. name = typeof object;
  6905. }
  6906. }
  6907. return name;
  6908. };
  6909. Tools.first = function (array, predicate) {
  6910. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6911. var el = array_1[_i];
  6912. if (predicate(el)) {
  6913. return el;
  6914. }
  6915. }
  6916. };
  6917. /**
  6918. * This method will return the name of the full name of the class, including its owning module (if any).
  6919. * 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).
  6920. * @param object the object to get the class name from
  6921. * @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.
  6922. */
  6923. Tools.getFullClassName = function (object, isType) {
  6924. if (isType === void 0) { isType = false; }
  6925. var className = null;
  6926. var moduleName = null;
  6927. if (!isType && object.getClassName) {
  6928. className = object.getClassName();
  6929. }
  6930. else {
  6931. if (object instanceof Object) {
  6932. var classObj = isType ? object : Object.getPrototypeOf(object);
  6933. className = classObj.constructor["__bjsclassName__"];
  6934. moduleName = classObj.constructor["__bjsmoduleName__"];
  6935. }
  6936. if (!className) {
  6937. className = typeof object;
  6938. }
  6939. }
  6940. if (!className) {
  6941. return null;
  6942. }
  6943. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6944. };
  6945. /**
  6946. * 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.
  6947. * @param array
  6948. */
  6949. Tools.arrayOrStringFeeder = function (array) {
  6950. return function (index) {
  6951. if (index >= array.length) {
  6952. return null;
  6953. }
  6954. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6955. if (val && val.getHashCode) {
  6956. val = val.getHashCode();
  6957. }
  6958. if (typeof val === "string") {
  6959. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6960. }
  6961. return val;
  6962. };
  6963. };
  6964. /**
  6965. * Compute the hashCode of a stream of number
  6966. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6967. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6968. * @return the hash code computed
  6969. */
  6970. Tools.hashCodeFromStream = function (feeder) {
  6971. // Based from here: http://stackoverflow.com/a/7616484/802124
  6972. var hash = 0;
  6973. var index = 0;
  6974. var chr = feeder(index++);
  6975. while (chr != null) {
  6976. hash = ((hash << 5) - hash) + chr;
  6977. hash |= 0; // Convert to 32bit integer
  6978. chr = feeder(index++);
  6979. }
  6980. return hash;
  6981. };
  6982. return Tools;
  6983. }());
  6984. Tools.BaseUrl = "";
  6985. Tools.CorsBehavior = "anonymous";
  6986. Tools.UseFallbackTexture = true;
  6987. // Used in case of a texture loading problem
  6988. 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";
  6989. // Logs
  6990. Tools._NoneLogLevel = 0;
  6991. Tools._MessageLogLevel = 1;
  6992. Tools._WarningLogLevel = 2;
  6993. Tools._ErrorLogLevel = 4;
  6994. Tools._LogCache = "";
  6995. Tools.errorsCount = 0;
  6996. Tools.Log = Tools._LogEnabled;
  6997. Tools.Warn = Tools._WarnEnabled;
  6998. Tools.Error = Tools._ErrorEnabled;
  6999. // Performances
  7000. Tools._PerformanceNoneLogLevel = 0;
  7001. Tools._PerformanceUserMarkLogLevel = 1;
  7002. Tools._PerformanceConsoleLogLevel = 2;
  7003. Tools._performance = window.performance;
  7004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7006. BABYLON.Tools = Tools;
  7007. /**
  7008. * This class is used to track a performance counter which is number based.
  7009. * The user has access to many properties which give statistics of different nature
  7010. *
  7011. * The implementer can track two kinds of Performance Counter: time and count
  7012. * 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.
  7013. * 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.
  7014. */
  7015. var PerfCounter = (function () {
  7016. function PerfCounter() {
  7017. this._startMonitoringTime = 0;
  7018. this._min = 0;
  7019. this._max = 0;
  7020. this._average = 0;
  7021. this._lastSecAverage = 0;
  7022. this._current = 0;
  7023. this._totalValueCount = 0;
  7024. this._totalAccumulated = 0;
  7025. this._lastSecAccumulated = 0;
  7026. this._lastSecTime = 0;
  7027. this._lastSecValueCount = 0;
  7028. }
  7029. Object.defineProperty(PerfCounter.prototype, "min", {
  7030. /**
  7031. * Returns the smallest value ever
  7032. */
  7033. get: function () {
  7034. return this._min;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(PerfCounter.prototype, "max", {
  7040. /**
  7041. * Returns the biggest value ever
  7042. */
  7043. get: function () {
  7044. return this._max;
  7045. },
  7046. enumerable: true,
  7047. configurable: true
  7048. });
  7049. Object.defineProperty(PerfCounter.prototype, "average", {
  7050. /**
  7051. * Returns the average value since the performance counter is running
  7052. */
  7053. get: function () {
  7054. return this._average;
  7055. },
  7056. enumerable: true,
  7057. configurable: true
  7058. });
  7059. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7060. /**
  7061. * Returns the average value of the last second the counter was monitored
  7062. */
  7063. get: function () {
  7064. return this._lastSecAverage;
  7065. },
  7066. enumerable: true,
  7067. configurable: true
  7068. });
  7069. Object.defineProperty(PerfCounter.prototype, "current", {
  7070. /**
  7071. * Returns the current value
  7072. */
  7073. get: function () {
  7074. return this._current;
  7075. },
  7076. enumerable: true,
  7077. configurable: true
  7078. });
  7079. Object.defineProperty(PerfCounter.prototype, "total", {
  7080. get: function () {
  7081. return this._totalAccumulated;
  7082. },
  7083. enumerable: true,
  7084. configurable: true
  7085. });
  7086. /**
  7087. * Call this method to start monitoring a new frame.
  7088. * 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.
  7089. */
  7090. PerfCounter.prototype.fetchNewFrame = function () {
  7091. this._totalValueCount++;
  7092. this._current = 0;
  7093. this._lastSecValueCount++;
  7094. };
  7095. /**
  7096. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7097. * @param newCount the count value to add to the monitored count
  7098. * @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.
  7099. */
  7100. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7101. this._current += newCount;
  7102. if (fetchResult) {
  7103. this._fetchResult();
  7104. }
  7105. };
  7106. /**
  7107. * Start monitoring this performance counter
  7108. */
  7109. PerfCounter.prototype.beginMonitoring = function () {
  7110. this._startMonitoringTime = Tools.Now;
  7111. };
  7112. /**
  7113. * Compute the time lapsed since the previous beginMonitoring() call.
  7114. * @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
  7115. */
  7116. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7117. if (newFrame === void 0) { newFrame = true; }
  7118. if (newFrame) {
  7119. this.fetchNewFrame();
  7120. }
  7121. var currentTime = Tools.Now;
  7122. this._current = currentTime - this._startMonitoringTime;
  7123. if (newFrame) {
  7124. this._fetchResult();
  7125. }
  7126. };
  7127. PerfCounter.prototype._fetchResult = function () {
  7128. this._totalAccumulated += this._current;
  7129. this._lastSecAccumulated += this._current;
  7130. // Min/Max update
  7131. this._min = Math.min(this._min, this._current);
  7132. this._max = Math.max(this._max, this._current);
  7133. this._average = this._totalAccumulated / this._totalValueCount;
  7134. // Reset last sec?
  7135. var now = Tools.Now;
  7136. if ((now - this._lastSecTime) > 1000) {
  7137. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7138. this._lastSecTime = now;
  7139. this._lastSecAccumulated = 0;
  7140. this._lastSecValueCount = 0;
  7141. }
  7142. };
  7143. return PerfCounter;
  7144. }());
  7145. BABYLON.PerfCounter = PerfCounter;
  7146. /**
  7147. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7148. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7149. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7150. * @param name The name of the class, case should be preserved
  7151. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7152. */
  7153. function className(name, module) {
  7154. return function (target) {
  7155. target["__bjsclassName__"] = name;
  7156. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7157. };
  7158. }
  7159. BABYLON.className = className;
  7160. /**
  7161. * An implementation of a loop for asynchronous functions.
  7162. */
  7163. var AsyncLoop = (function () {
  7164. /**
  7165. * Constroctor.
  7166. * @param iterations the number of iterations.
  7167. * @param _fn the function to run each iteration
  7168. * @param _successCallback the callback that will be called upon succesful execution
  7169. * @param offset starting offset.
  7170. */
  7171. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7172. if (offset === void 0) { offset = 0; }
  7173. this.iterations = iterations;
  7174. this._fn = _fn;
  7175. this._successCallback = _successCallback;
  7176. this.index = offset - 1;
  7177. this._done = false;
  7178. }
  7179. /**
  7180. * Execute the next iteration. Must be called after the last iteration was finished.
  7181. */
  7182. AsyncLoop.prototype.executeNext = function () {
  7183. if (!this._done) {
  7184. if (this.index + 1 < this.iterations) {
  7185. ++this.index;
  7186. this._fn(this);
  7187. }
  7188. else {
  7189. this.breakLoop();
  7190. }
  7191. }
  7192. };
  7193. /**
  7194. * Break the loop and run the success callback.
  7195. */
  7196. AsyncLoop.prototype.breakLoop = function () {
  7197. this._done = true;
  7198. this._successCallback();
  7199. };
  7200. /**
  7201. * Helper function
  7202. */
  7203. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7204. if (offset === void 0) { offset = 0; }
  7205. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7206. loop.executeNext();
  7207. return loop;
  7208. };
  7209. /**
  7210. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7211. * @param iterations total number of iterations
  7212. * @param syncedIterations number of synchronous iterations in each async iteration.
  7213. * @param fn the function to call each iteration.
  7214. * @param callback a success call back that will be called when iterating stops.
  7215. * @param breakFunction a break condition (optional)
  7216. * @param timeout timeout settings for the setTimeout function. default - 0.
  7217. * @constructor
  7218. */
  7219. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7220. if (timeout === void 0) { timeout = 0; }
  7221. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7222. if (breakFunction && breakFunction())
  7223. loop.breakLoop();
  7224. else {
  7225. setTimeout(function () {
  7226. for (var i = 0; i < syncedIterations; ++i) {
  7227. var iteration = (loop.index * syncedIterations) + i;
  7228. if (iteration >= iterations)
  7229. break;
  7230. fn(iteration);
  7231. if (breakFunction && breakFunction()) {
  7232. loop.breakLoop();
  7233. break;
  7234. }
  7235. }
  7236. loop.executeNext();
  7237. }, timeout);
  7238. }
  7239. }, callback);
  7240. };
  7241. return AsyncLoop;
  7242. }());
  7243. BABYLON.AsyncLoop = AsyncLoop;
  7244. })(BABYLON || (BABYLON = {}));
  7245. //# sourceMappingURL=babylon.tools.js.map
  7246. var BABYLON;
  7247. (function (BABYLON) {
  7248. var Internals;
  7249. (function (Internals) {
  7250. var _AlphaState = (function () {
  7251. /**
  7252. * Initializes the state.
  7253. */
  7254. function _AlphaState() {
  7255. this._isAlphaBlendDirty = false;
  7256. this._isBlendFunctionParametersDirty = false;
  7257. this._alphaBlend = false;
  7258. this._blendFunctionParameters = new Array(4);
  7259. this.reset();
  7260. }
  7261. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7262. get: function () {
  7263. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7264. },
  7265. enumerable: true,
  7266. configurable: true
  7267. });
  7268. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7269. get: function () {
  7270. return this._alphaBlend;
  7271. },
  7272. set: function (value) {
  7273. if (this._alphaBlend === value) {
  7274. return;
  7275. }
  7276. this._alphaBlend = value;
  7277. this._isAlphaBlendDirty = true;
  7278. },
  7279. enumerable: true,
  7280. configurable: true
  7281. });
  7282. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7283. if (this._blendFunctionParameters[0] === value0 &&
  7284. this._blendFunctionParameters[1] === value1 &&
  7285. this._blendFunctionParameters[2] === value2 &&
  7286. this._blendFunctionParameters[3] === value3) {
  7287. return;
  7288. }
  7289. this._blendFunctionParameters[0] = value0;
  7290. this._blendFunctionParameters[1] = value1;
  7291. this._blendFunctionParameters[2] = value2;
  7292. this._blendFunctionParameters[3] = value3;
  7293. this._isBlendFunctionParametersDirty = true;
  7294. };
  7295. _AlphaState.prototype.reset = function () {
  7296. this._alphaBlend = false;
  7297. this._blendFunctionParameters[0] = null;
  7298. this._blendFunctionParameters[1] = null;
  7299. this._blendFunctionParameters[2] = null;
  7300. this._blendFunctionParameters[3] = null;
  7301. this._isAlphaBlendDirty = true;
  7302. this._isBlendFunctionParametersDirty = false;
  7303. };
  7304. _AlphaState.prototype.apply = function (gl) {
  7305. if (!this.isDirty) {
  7306. return;
  7307. }
  7308. // Alpha blend
  7309. if (this._isAlphaBlendDirty) {
  7310. if (this._alphaBlend) {
  7311. gl.enable(gl.BLEND);
  7312. }
  7313. else {
  7314. gl.disable(gl.BLEND);
  7315. }
  7316. this._isAlphaBlendDirty = false;
  7317. }
  7318. // Alpha function
  7319. if (this._isBlendFunctionParametersDirty) {
  7320. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7321. this._isBlendFunctionParametersDirty = false;
  7322. }
  7323. };
  7324. return _AlphaState;
  7325. }());
  7326. Internals._AlphaState = _AlphaState;
  7327. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7328. })(BABYLON || (BABYLON = {}));
  7329. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7330. var BABYLON;
  7331. (function (BABYLON) {
  7332. var Internals;
  7333. (function (Internals) {
  7334. var _DepthCullingState = (function () {
  7335. /**
  7336. * Initializes the state.
  7337. */
  7338. function _DepthCullingState() {
  7339. this._isDepthTestDirty = false;
  7340. this._isDepthMaskDirty = false;
  7341. this._isDepthFuncDirty = false;
  7342. this._isCullFaceDirty = false;
  7343. this._isCullDirty = false;
  7344. this._isZOffsetDirty = false;
  7345. this.reset();
  7346. }
  7347. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7348. get: function () {
  7349. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7355. get: function () {
  7356. return this._zOffset;
  7357. },
  7358. set: function (value) {
  7359. if (this._zOffset === value) {
  7360. return;
  7361. }
  7362. this._zOffset = value;
  7363. this._isZOffsetDirty = true;
  7364. },
  7365. enumerable: true,
  7366. configurable: true
  7367. });
  7368. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7369. get: function () {
  7370. return this._cullFace;
  7371. },
  7372. set: function (value) {
  7373. if (this._cullFace === value) {
  7374. return;
  7375. }
  7376. this._cullFace = value;
  7377. this._isCullFaceDirty = true;
  7378. },
  7379. enumerable: true,
  7380. configurable: true
  7381. });
  7382. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7383. get: function () {
  7384. return this._cull;
  7385. },
  7386. set: function (value) {
  7387. if (this._cull === value) {
  7388. return;
  7389. }
  7390. this._cull = value;
  7391. this._isCullDirty = true;
  7392. },
  7393. enumerable: true,
  7394. configurable: true
  7395. });
  7396. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7397. get: function () {
  7398. return this._depthFunc;
  7399. },
  7400. set: function (value) {
  7401. if (this._depthFunc === value) {
  7402. return;
  7403. }
  7404. this._depthFunc = value;
  7405. this._isDepthFuncDirty = true;
  7406. },
  7407. enumerable: true,
  7408. configurable: true
  7409. });
  7410. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7411. get: function () {
  7412. return this._depthMask;
  7413. },
  7414. set: function (value) {
  7415. if (this._depthMask === value) {
  7416. return;
  7417. }
  7418. this._depthMask = value;
  7419. this._isDepthMaskDirty = true;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7425. get: function () {
  7426. return this._depthTest;
  7427. },
  7428. set: function (value) {
  7429. if (this._depthTest === value) {
  7430. return;
  7431. }
  7432. this._depthTest = value;
  7433. this._isDepthTestDirty = true;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. _DepthCullingState.prototype.reset = function () {
  7439. this._depthMask = true;
  7440. this._depthTest = true;
  7441. this._depthFunc = null;
  7442. this._cullFace = null;
  7443. this._cull = null;
  7444. this._zOffset = 0;
  7445. this._isDepthTestDirty = true;
  7446. this._isDepthMaskDirty = true;
  7447. this._isDepthFuncDirty = false;
  7448. this._isCullFaceDirty = false;
  7449. this._isCullDirty = false;
  7450. this._isZOffsetDirty = false;
  7451. };
  7452. _DepthCullingState.prototype.apply = function (gl) {
  7453. if (!this.isDirty) {
  7454. return;
  7455. }
  7456. // Cull
  7457. if (this._isCullDirty) {
  7458. if (this.cull) {
  7459. gl.enable(gl.CULL_FACE);
  7460. }
  7461. else {
  7462. gl.disable(gl.CULL_FACE);
  7463. }
  7464. this._isCullDirty = false;
  7465. }
  7466. // Cull face
  7467. if (this._isCullFaceDirty) {
  7468. gl.cullFace(this.cullFace);
  7469. this._isCullFaceDirty = false;
  7470. }
  7471. // Depth mask
  7472. if (this._isDepthMaskDirty) {
  7473. gl.depthMask(this.depthMask);
  7474. this._isDepthMaskDirty = false;
  7475. }
  7476. // Depth test
  7477. if (this._isDepthTestDirty) {
  7478. if (this.depthTest) {
  7479. gl.enable(gl.DEPTH_TEST);
  7480. }
  7481. else {
  7482. gl.disable(gl.DEPTH_TEST);
  7483. }
  7484. this._isDepthTestDirty = false;
  7485. }
  7486. // Depth func
  7487. if (this._isDepthFuncDirty) {
  7488. gl.depthFunc(this.depthFunc);
  7489. this._isDepthFuncDirty = false;
  7490. }
  7491. // zOffset
  7492. if (this._isZOffsetDirty) {
  7493. if (this.zOffset) {
  7494. gl.enable(gl.POLYGON_OFFSET_FILL);
  7495. gl.polygonOffset(this.zOffset, 0);
  7496. }
  7497. else {
  7498. gl.disable(gl.POLYGON_OFFSET_FILL);
  7499. }
  7500. this._isZOffsetDirty = false;
  7501. }
  7502. };
  7503. return _DepthCullingState;
  7504. }());
  7505. Internals._DepthCullingState = _DepthCullingState;
  7506. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7507. })(BABYLON || (BABYLON = {}));
  7508. //# sourceMappingURL=babylon.depthCullingState.js.map
  7509. var BABYLON;
  7510. (function (BABYLON) {
  7511. var Internals;
  7512. (function (Internals) {
  7513. var _StencilState = (function () {
  7514. function _StencilState() {
  7515. this._isStencilTestDirty = false;
  7516. this._isStencilMaskDirty = false;
  7517. this._isStencilFuncDirty = false;
  7518. this._isStencilOpDirty = false;
  7519. this.reset();
  7520. }
  7521. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7522. get: function () {
  7523. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7524. },
  7525. enumerable: true,
  7526. configurable: true
  7527. });
  7528. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7529. get: function () {
  7530. return this._stencilFunc;
  7531. },
  7532. set: function (value) {
  7533. if (this._stencilFunc === value) {
  7534. return;
  7535. }
  7536. this._stencilFunc = value;
  7537. this._isStencilFuncDirty = true;
  7538. },
  7539. enumerable: true,
  7540. configurable: true
  7541. });
  7542. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7543. get: function () {
  7544. return this._stencilFuncRef;
  7545. },
  7546. set: function (value) {
  7547. if (this._stencilFuncRef === value) {
  7548. return;
  7549. }
  7550. this._stencilFuncRef = value;
  7551. this._isStencilFuncDirty = true;
  7552. },
  7553. enumerable: true,
  7554. configurable: true
  7555. });
  7556. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7557. get: function () {
  7558. return this._stencilFuncMask;
  7559. },
  7560. set: function (value) {
  7561. if (this._stencilFuncMask === value) {
  7562. return;
  7563. }
  7564. this._stencilFuncMask = value;
  7565. this._isStencilFuncDirty = true;
  7566. },
  7567. enumerable: true,
  7568. configurable: true
  7569. });
  7570. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7571. get: function () {
  7572. return this._stencilOpStencilFail;
  7573. },
  7574. set: function (value) {
  7575. if (this._stencilOpStencilFail === value) {
  7576. return;
  7577. }
  7578. this._stencilOpStencilFail = value;
  7579. this._isStencilOpDirty = true;
  7580. },
  7581. enumerable: true,
  7582. configurable: true
  7583. });
  7584. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7585. get: function () {
  7586. return this._stencilOpDepthFail;
  7587. },
  7588. set: function (value) {
  7589. if (this._stencilOpDepthFail === value) {
  7590. return;
  7591. }
  7592. this._stencilOpDepthFail = value;
  7593. this._isStencilOpDirty = true;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7599. get: function () {
  7600. return this._stencilOpStencilDepthPass;
  7601. },
  7602. set: function (value) {
  7603. if (this._stencilOpStencilDepthPass === value) {
  7604. return;
  7605. }
  7606. this._stencilOpStencilDepthPass = value;
  7607. this._isStencilOpDirty = true;
  7608. },
  7609. enumerable: true,
  7610. configurable: true
  7611. });
  7612. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7613. get: function () {
  7614. return this._stencilMask;
  7615. },
  7616. set: function (value) {
  7617. if (this._stencilMask === value) {
  7618. return;
  7619. }
  7620. this._stencilMask = value;
  7621. this._isStencilMaskDirty = true;
  7622. },
  7623. enumerable: true,
  7624. configurable: true
  7625. });
  7626. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7627. get: function () {
  7628. return this._stencilTest;
  7629. },
  7630. set: function (value) {
  7631. if (this._stencilTest === value) {
  7632. return;
  7633. }
  7634. this._stencilTest = value;
  7635. this._isStencilTestDirty = true;
  7636. },
  7637. enumerable: true,
  7638. configurable: true
  7639. });
  7640. _StencilState.prototype.reset = function () {
  7641. this._stencilTest = false;
  7642. this._stencilMask = 0xFF;
  7643. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7644. this._stencilFuncRef = 1;
  7645. this._stencilFuncMask = 0xFF;
  7646. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7647. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7648. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7649. this._isStencilTestDirty = true;
  7650. this._isStencilMaskDirty = true;
  7651. this._isStencilFuncDirty = true;
  7652. this._isStencilOpDirty = true;
  7653. };
  7654. _StencilState.prototype.apply = function (gl) {
  7655. if (!this.isDirty) {
  7656. return;
  7657. }
  7658. // Stencil test
  7659. if (this._isStencilTestDirty) {
  7660. if (this.stencilTest) {
  7661. gl.enable(gl.STENCIL_TEST);
  7662. }
  7663. else {
  7664. gl.disable(gl.STENCIL_TEST);
  7665. }
  7666. this._isStencilTestDirty = false;
  7667. }
  7668. // Stencil mask
  7669. if (this._isStencilMaskDirty) {
  7670. gl.stencilMask(this.stencilMask);
  7671. this._isStencilMaskDirty = false;
  7672. }
  7673. // Stencil func
  7674. if (this._isStencilFuncDirty) {
  7675. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7676. this._isStencilFuncDirty = false;
  7677. }
  7678. // Stencil op
  7679. if (this._isStencilOpDirty) {
  7680. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7681. this._isStencilOpDirty = false;
  7682. }
  7683. };
  7684. return _StencilState;
  7685. }());
  7686. Internals._StencilState = _StencilState;
  7687. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7688. })(BABYLON || (BABYLON = {}));
  7689. //# sourceMappingURL=babylon.stencilState.js.map
  7690. var BABYLON;
  7691. (function (BABYLON) {
  7692. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7693. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7694. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7695. gl.compileShader(shader);
  7696. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7697. throw new Error(gl.getShaderInfoLog(shader));
  7698. }
  7699. return shader;
  7700. };
  7701. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7702. var magFilter = gl.NEAREST;
  7703. var minFilter = gl.NEAREST;
  7704. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7705. magFilter = gl.LINEAR;
  7706. if (generateMipMaps) {
  7707. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7708. }
  7709. else {
  7710. minFilter = gl.LINEAR;
  7711. }
  7712. }
  7713. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7714. magFilter = gl.LINEAR;
  7715. if (generateMipMaps) {
  7716. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7717. }
  7718. else {
  7719. minFilter = gl.LINEAR;
  7720. }
  7721. }
  7722. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7723. magFilter = gl.NEAREST;
  7724. if (generateMipMaps) {
  7725. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7726. }
  7727. else {
  7728. minFilter = gl.NEAREST;
  7729. }
  7730. }
  7731. return {
  7732. min: minFilter,
  7733. mag: magFilter
  7734. };
  7735. };
  7736. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7737. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7738. var engine = scene.getEngine();
  7739. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7740. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7741. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7742. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7743. texture._baseWidth = width;
  7744. texture._baseHeight = height;
  7745. texture._width = potWidth;
  7746. texture._height = potHeight;
  7747. texture.isReady = true;
  7748. processFunction(potWidth, potHeight);
  7749. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7750. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7751. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7752. if (!noMipmap && !isCompressed) {
  7753. gl.generateMipmap(gl.TEXTURE_2D);
  7754. }
  7755. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7756. engine.resetTextureCache();
  7757. scene._removePendingData(texture);
  7758. texture.onLoadedCallbacks.forEach(function (callback) {
  7759. callback();
  7760. });
  7761. texture.onLoadedCallbacks = [];
  7762. };
  7763. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7764. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7765. var img;
  7766. var onload = function () {
  7767. loadedImages[index] = img;
  7768. loadedImages._internalCount++;
  7769. scene._removePendingData(img);
  7770. if (loadedImages._internalCount === 6) {
  7771. onfinish(loadedImages);
  7772. }
  7773. };
  7774. var onerror = function () {
  7775. scene._removePendingData(img);
  7776. if (onErrorCallBack) {
  7777. onErrorCallBack();
  7778. }
  7779. };
  7780. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7781. scene._addPendingData(img);
  7782. };
  7783. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7784. if (onError === void 0) { onError = null; }
  7785. var loadedImages = [];
  7786. loadedImages._internalCount = 0;
  7787. for (var index = 0; index < 6; index++) {
  7788. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7789. }
  7790. };
  7791. var InstancingAttributeInfo = (function () {
  7792. function InstancingAttributeInfo() {
  7793. }
  7794. return InstancingAttributeInfo;
  7795. }());
  7796. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7797. var EngineCapabilities = (function () {
  7798. function EngineCapabilities() {
  7799. }
  7800. return EngineCapabilities;
  7801. }());
  7802. BABYLON.EngineCapabilities = EngineCapabilities;
  7803. /**
  7804. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7805. */
  7806. var Engine = (function () {
  7807. /**
  7808. * @constructor
  7809. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7810. * @param {boolean} [antialias] - enable antialias
  7811. * @param options - further options to be sent to the getContext function
  7812. */
  7813. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7814. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7815. var _this = this;
  7816. // Public members
  7817. this.isFullscreen = false;
  7818. this.isPointerLock = false;
  7819. this.cullBackFaces = true;
  7820. this.renderEvenInBackground = true;
  7821. // To enable/disable IDB support and avoid XHR on .manifest
  7822. this.enableOfflineSupport = true;
  7823. this.scenes = new Array();
  7824. this._windowIsBackground = false;
  7825. this._webGLVersion = 1.0;
  7826. this._badOS = false;
  7827. this._drawCalls = new BABYLON.PerfCounter();
  7828. this._renderingQueueLaunched = false;
  7829. this._activeRenderLoops = [];
  7830. // FPS
  7831. this.fpsRange = 60;
  7832. this.previousFramesDuration = [];
  7833. this.fps = 60;
  7834. this.deltaTime = 0;
  7835. // States
  7836. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7837. this._stencilState = new BABYLON.Internals._StencilState();
  7838. this._alphaState = new BABYLON.Internals._AlphaState();
  7839. this._alphaMode = Engine.ALPHA_DISABLE;
  7840. // Cache
  7841. this._loadedTexturesCache = new Array();
  7842. this._maxTextureChannels = 16;
  7843. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7844. this._compiledEffects = {};
  7845. this._vertexAttribArraysEnabled = [];
  7846. this._uintIndicesCurrentlySet = false;
  7847. this._currentBoundBuffer = new Array();
  7848. this._currentBufferPointers = [];
  7849. this._currentInstanceLocations = new Array();
  7850. this._currentInstanceBuffers = new Array();
  7851. this._vaoRecordInProgress = false;
  7852. this._mustWipeVertexAttributes = false;
  7853. // Hardware supported Compressed Textures
  7854. this._texturesSupported = new Array();
  7855. this._onVRFullScreenTriggered = function () {
  7856. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7857. //get the old size before we change
  7858. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7859. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7860. //get the width and height, change the render size
  7861. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7862. var width, height;
  7863. _this.setHardwareScalingLevel(1);
  7864. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7865. }
  7866. else {
  7867. //When the specs are implemented, need to uncomment this.
  7868. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7869. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7870. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7871. _this._vrDisplayEnabled = undefined;
  7872. }
  7873. };
  7874. this._renderingCanvas = canvas;
  7875. Engine.Instances.push(this);
  7876. this._externalData = new BABYLON.StringDictionary();
  7877. options = options || {};
  7878. if (antialias != null) {
  7879. options.antialias = antialias;
  7880. }
  7881. if (options.preserveDrawingBuffer === undefined) {
  7882. options.preserveDrawingBuffer = false;
  7883. }
  7884. // GL
  7885. if (!options.disableWebGL2Support) {
  7886. try {
  7887. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7888. if (this._gl) {
  7889. this._webGLVersion = 2.0;
  7890. }
  7891. }
  7892. catch (e) {
  7893. }
  7894. }
  7895. if (!this._gl) {
  7896. if (!canvas) {
  7897. throw new Error("The provided canvas is null or undefined.");
  7898. }
  7899. try {
  7900. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7901. }
  7902. catch (e) {
  7903. throw new Error("WebGL not supported");
  7904. }
  7905. }
  7906. if (!this._gl) {
  7907. throw new Error("WebGL not supported");
  7908. }
  7909. this._onBlur = function () {
  7910. _this._windowIsBackground = true;
  7911. };
  7912. this._onFocus = function () {
  7913. _this._windowIsBackground = false;
  7914. };
  7915. window.addEventListener("blur", this._onBlur);
  7916. window.addEventListener("focus", this._onFocus);
  7917. // Viewport
  7918. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7919. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7920. this.resize();
  7921. // Caps
  7922. this._isStencilEnable = options.stencil;
  7923. this._caps = new EngineCapabilities();
  7924. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7925. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7926. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7927. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7928. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7929. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7930. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7931. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7932. // Infos
  7933. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7934. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7935. if (rendererInfo != null) {
  7936. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7937. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7938. }
  7939. if (!this._glVendor) {
  7940. this._glVendor = "Unknown vendor";
  7941. }
  7942. if (!this._glRenderer) {
  7943. this._glRenderer = "Unknown renderer";
  7944. }
  7945. // Extensions
  7946. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7947. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7948. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7949. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7950. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7951. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7952. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7953. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  7954. 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');
  7955. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7956. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7957. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7958. this._caps.highPrecisionShaderSupported = true;
  7959. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7960. // Checks if some of the format renders first to allow the use of webgl inspector.
  7961. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7962. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7963. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7964. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7965. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7966. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7967. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7968. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7969. // Vertex array object
  7970. if (this._webGLVersion > 1) {
  7971. this._caps.vertexArrayObject = true;
  7972. }
  7973. else {
  7974. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7975. if (vertexArrayObjectExtension != null) {
  7976. this._caps.vertexArrayObject = true;
  7977. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7978. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7979. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7980. }
  7981. else {
  7982. this._caps.vertexArrayObject = false;
  7983. }
  7984. }
  7985. // Instances count
  7986. if (this._webGLVersion > 1) {
  7987. this._caps.instancedArrays = true;
  7988. }
  7989. else {
  7990. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7991. if (instanceExtension != null) {
  7992. this._caps.instancedArrays = true;
  7993. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7994. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7995. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7996. }
  7997. else {
  7998. this._caps.instancedArrays = false;
  7999. }
  8000. }
  8001. // Intelligently add supported compressed formats in order to check for.
  8002. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8003. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8004. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8005. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8006. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  8007. if (this._caps.astc)
  8008. this.texturesSupported.push('-astc.ktx');
  8009. if (this._caps.s3tc)
  8010. this.texturesSupported.push('-dxt.ktx');
  8011. if (this._caps.pvrtc)
  8012. this.texturesSupported.push('-pvrtc.ktx');
  8013. if (this._caps.etc2)
  8014. this.texturesSupported.push('-etc2.ktx');
  8015. if (this._caps.atc)
  8016. this.texturesSupported.push('-atc.ktx');
  8017. if (this._caps.etc1)
  8018. this.texturesSupported.push('-etc1.ktx');
  8019. if (this._gl.getShaderPrecisionFormat) {
  8020. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8021. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8022. }
  8023. // Depth buffer
  8024. this.setDepthBuffer(true);
  8025. this.setDepthFunctionToLessOrEqual();
  8026. this.setDepthWrite(true);
  8027. // Fullscreen
  8028. this._onFullscreenChange = function () {
  8029. if (document.fullscreen !== undefined) {
  8030. _this.isFullscreen = document.fullscreen;
  8031. }
  8032. else if (document.mozFullScreen !== undefined) {
  8033. _this.isFullscreen = document.mozFullScreen;
  8034. }
  8035. else if (document.webkitIsFullScreen !== undefined) {
  8036. _this.isFullscreen = document.webkitIsFullScreen;
  8037. }
  8038. else if (document.msIsFullScreen !== undefined) {
  8039. _this.isFullscreen = document.msIsFullScreen;
  8040. }
  8041. // Pointer lock
  8042. if (_this.isFullscreen && _this._pointerLockRequested) {
  8043. canvas.requestPointerLock = canvas.requestPointerLock ||
  8044. canvas.msRequestPointerLock ||
  8045. canvas.mozRequestPointerLock ||
  8046. canvas.webkitRequestPointerLock;
  8047. if (canvas.requestPointerLock) {
  8048. canvas.requestPointerLock();
  8049. }
  8050. }
  8051. };
  8052. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8053. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8054. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8055. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8056. // Pointer lock
  8057. this._onPointerLockChange = function () {
  8058. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8059. document.webkitPointerLockElement === canvas ||
  8060. document.msPointerLockElement === canvas ||
  8061. document.pointerLockElement === canvas);
  8062. };
  8063. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8064. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8065. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8066. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8067. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  8068. Engine.audioEngine = new BABYLON.AudioEngine();
  8069. }
  8070. //default loading screen
  8071. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8072. //Load WebVR Devices
  8073. if (options.autoEnableWebVR) {
  8074. this.initWebVR();
  8075. }
  8076. //Detect if we are running on a faulty buggy OS.
  8077. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8078. //ua sniffing is the tool of the devil.
  8079. this._badOS = regexp.test(navigator.userAgent);
  8080. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8081. }
  8082. Object.defineProperty(Engine, "LastCreatedEngine", {
  8083. get: function () {
  8084. if (Engine.Instances.length === 0) {
  8085. return null;
  8086. }
  8087. return Engine.Instances[Engine.Instances.length - 1];
  8088. },
  8089. enumerable: true,
  8090. configurable: true
  8091. });
  8092. Object.defineProperty(Engine, "LastCreatedScene", {
  8093. get: function () {
  8094. var lastCreatedEngine = Engine.LastCreatedEngine;
  8095. if (!lastCreatedEngine) {
  8096. return null;
  8097. }
  8098. if (lastCreatedEngine.scenes.length === 0) {
  8099. return null;
  8100. }
  8101. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8102. },
  8103. enumerable: true,
  8104. configurable: true
  8105. });
  8106. Object.defineProperty(Engine, "NEVER", {
  8107. get: function () {
  8108. return Engine._NEVER;
  8109. },
  8110. enumerable: true,
  8111. configurable: true
  8112. });
  8113. Object.defineProperty(Engine, "ALWAYS", {
  8114. get: function () {
  8115. return Engine._ALWAYS;
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. Object.defineProperty(Engine, "LESS", {
  8121. get: function () {
  8122. return Engine._LESS;
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine, "EQUAL", {
  8128. get: function () {
  8129. return Engine._EQUAL;
  8130. },
  8131. enumerable: true,
  8132. configurable: true
  8133. });
  8134. Object.defineProperty(Engine, "LEQUAL", {
  8135. get: function () {
  8136. return Engine._LEQUAL;
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. Object.defineProperty(Engine, "GREATER", {
  8142. get: function () {
  8143. return Engine._GREATER;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(Engine, "GEQUAL", {
  8149. get: function () {
  8150. return Engine._GEQUAL;
  8151. },
  8152. enumerable: true,
  8153. configurable: true
  8154. });
  8155. Object.defineProperty(Engine, "NOTEQUAL", {
  8156. get: function () {
  8157. return Engine._NOTEQUAL;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(Engine, "KEEP", {
  8163. get: function () {
  8164. return Engine._KEEP;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(Engine, "REPLACE", {
  8170. get: function () {
  8171. return Engine._REPLACE;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "INCR", {
  8177. get: function () {
  8178. return Engine._INCR;
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. Object.defineProperty(Engine, "DECR", {
  8184. get: function () {
  8185. return Engine._DECR;
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(Engine, "INVERT", {
  8191. get: function () {
  8192. return Engine._INVERT;
  8193. },
  8194. enumerable: true,
  8195. configurable: true
  8196. });
  8197. Object.defineProperty(Engine, "INCR_WRAP", {
  8198. get: function () {
  8199. return Engine._INCR_WRAP;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Engine, "DECR_WRAP", {
  8205. get: function () {
  8206. return Engine._DECR_WRAP;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8212. get: function () {
  8213. return Engine._ALPHA_DISABLE;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8219. get: function () {
  8220. return Engine._ALPHA_ONEONE;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Engine, "ALPHA_ADD", {
  8226. get: function () {
  8227. return Engine._ALPHA_ADD;
  8228. },
  8229. enumerable: true,
  8230. configurable: true
  8231. });
  8232. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8233. get: function () {
  8234. return Engine._ALPHA_COMBINE;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8240. get: function () {
  8241. return Engine._ALPHA_SUBTRACT;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8247. get: function () {
  8248. return Engine._ALPHA_MULTIPLY;
  8249. },
  8250. enumerable: true,
  8251. configurable: true
  8252. });
  8253. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8254. get: function () {
  8255. return Engine._ALPHA_MAXIMIZED;
  8256. },
  8257. enumerable: true,
  8258. configurable: true
  8259. });
  8260. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8261. get: function () {
  8262. return Engine._ALPHA_PREMULTIPLIED;
  8263. },
  8264. enumerable: true,
  8265. configurable: true
  8266. });
  8267. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8268. get: function () {
  8269. return Engine._DELAYLOADSTATE_NONE;
  8270. },
  8271. enumerable: true,
  8272. configurable: true
  8273. });
  8274. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8275. get: function () {
  8276. return Engine._DELAYLOADSTATE_LOADED;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8282. get: function () {
  8283. return Engine._DELAYLOADSTATE_LOADING;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8289. get: function () {
  8290. return Engine._DELAYLOADSTATE_NOTLOADED;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8296. get: function () {
  8297. return Engine._TEXTUREFORMAT_ALPHA;
  8298. },
  8299. enumerable: true,
  8300. configurable: true
  8301. });
  8302. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8303. get: function () {
  8304. return Engine._TEXTUREFORMAT_LUMINANCE;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8310. get: function () {
  8311. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8317. get: function () {
  8318. return Engine._TEXTUREFORMAT_RGB;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8324. get: function () {
  8325. return Engine._TEXTUREFORMAT_RGBA;
  8326. },
  8327. enumerable: true,
  8328. configurable: true
  8329. });
  8330. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8331. get: function () {
  8332. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8333. },
  8334. enumerable: true,
  8335. configurable: true
  8336. });
  8337. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8338. get: function () {
  8339. return Engine._TEXTURETYPE_FLOAT;
  8340. },
  8341. enumerable: true,
  8342. configurable: true
  8343. });
  8344. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8345. get: function () {
  8346. return Engine._TEXTURETYPE_HALF_FLOAT;
  8347. },
  8348. enumerable: true,
  8349. configurable: true
  8350. });
  8351. Object.defineProperty(Engine, "Version", {
  8352. get: function () {
  8353. return "3.0-alpha";
  8354. },
  8355. enumerable: true,
  8356. configurable: true
  8357. });
  8358. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8359. get: function () {
  8360. return this._texturesSupported;
  8361. },
  8362. enumerable: true,
  8363. configurable: true
  8364. });
  8365. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8366. get: function () {
  8367. return this._textureFormatInUse;
  8368. },
  8369. enumerable: true,
  8370. configurable: true
  8371. });
  8372. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8373. get: function () {
  8374. return this._webGLVersion;
  8375. },
  8376. enumerable: true,
  8377. configurable: true
  8378. });
  8379. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8380. /**
  8381. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8382. */
  8383. get: function () {
  8384. return this._isStencilEnable;
  8385. },
  8386. enumerable: true,
  8387. configurable: true
  8388. });
  8389. Engine.prototype._prepareWorkingCanvas = function () {
  8390. if (this._workingCanvas) {
  8391. return;
  8392. }
  8393. this._workingCanvas = document.createElement("canvas");
  8394. this._workingContext = this._workingCanvas.getContext("2d");
  8395. };
  8396. Engine.prototype.resetTextureCache = function () {
  8397. for (var index = 0; index < this._maxTextureChannels; index++) {
  8398. this._activeTexturesCache[index] = null;
  8399. }
  8400. };
  8401. Engine.prototype.getGlInfo = function () {
  8402. return {
  8403. vendor: this._glVendor,
  8404. renderer: this._glRenderer,
  8405. version: this._glVersion
  8406. };
  8407. };
  8408. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8409. if (useScreen === void 0) { useScreen = false; }
  8410. var viewport = camera.viewport;
  8411. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8412. };
  8413. Engine.prototype.getRenderWidth = function (useScreen) {
  8414. if (useScreen === void 0) { useScreen = false; }
  8415. if (!useScreen && this._currentRenderTarget) {
  8416. return this._currentRenderTarget._width;
  8417. }
  8418. return this._renderingCanvas.width;
  8419. };
  8420. Engine.prototype.getRenderHeight = function (useScreen) {
  8421. if (useScreen === void 0) { useScreen = false; }
  8422. if (!useScreen && this._currentRenderTarget) {
  8423. return this._currentRenderTarget._height;
  8424. }
  8425. return this._renderingCanvas.height;
  8426. };
  8427. Engine.prototype.getRenderingCanvas = function () {
  8428. return this._renderingCanvas;
  8429. };
  8430. Engine.prototype.getRenderingCanvasClientRect = function () {
  8431. return this._renderingCanvas.getBoundingClientRect();
  8432. };
  8433. Engine.prototype.setHardwareScalingLevel = function (level) {
  8434. this._hardwareScalingLevel = level;
  8435. this.resize();
  8436. };
  8437. Engine.prototype.getHardwareScalingLevel = function () {
  8438. return this._hardwareScalingLevel;
  8439. };
  8440. Engine.prototype.getLoadedTexturesCache = function () {
  8441. return this._loadedTexturesCache;
  8442. };
  8443. Engine.prototype.getCaps = function () {
  8444. return this._caps;
  8445. };
  8446. Object.defineProperty(Engine.prototype, "drawCalls", {
  8447. get: function () {
  8448. return this._drawCalls.current;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8454. get: function () {
  8455. return this._drawCalls;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Engine.prototype.getDepthFunction = function () {
  8461. return this._depthCullingState.depthFunc;
  8462. };
  8463. Engine.prototype.setDepthFunction = function (depthFunc) {
  8464. this._depthCullingState.depthFunc = depthFunc;
  8465. };
  8466. Engine.prototype.setDepthFunctionToGreater = function () {
  8467. this._depthCullingState.depthFunc = this._gl.GREATER;
  8468. };
  8469. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8470. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8471. };
  8472. Engine.prototype.setDepthFunctionToLess = function () {
  8473. this._depthCullingState.depthFunc = this._gl.LESS;
  8474. };
  8475. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8476. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8477. };
  8478. Engine.prototype.getStencilBuffer = function () {
  8479. return this._stencilState.stencilTest;
  8480. };
  8481. Engine.prototype.setStencilBuffer = function (enable) {
  8482. this._stencilState.stencilTest = enable;
  8483. };
  8484. Engine.prototype.getStencilMask = function () {
  8485. return this._stencilState.stencilMask;
  8486. };
  8487. Engine.prototype.setStencilMask = function (mask) {
  8488. this._stencilState.stencilMask = mask;
  8489. };
  8490. Engine.prototype.getStencilFunction = function () {
  8491. return this._stencilState.stencilFunc;
  8492. };
  8493. Engine.prototype.getStencilFunctionReference = function () {
  8494. return this._stencilState.stencilFuncRef;
  8495. };
  8496. Engine.prototype.getStencilFunctionMask = function () {
  8497. return this._stencilState.stencilFuncMask;
  8498. };
  8499. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8500. this._stencilState.stencilFunc = stencilFunc;
  8501. };
  8502. Engine.prototype.setStencilFunctionReference = function (reference) {
  8503. this._stencilState.stencilFuncRef = reference;
  8504. };
  8505. Engine.prototype.setStencilFunctionMask = function (mask) {
  8506. this._stencilState.stencilFuncMask = mask;
  8507. };
  8508. Engine.prototype.getStencilOperationFail = function () {
  8509. return this._stencilState.stencilOpStencilFail;
  8510. };
  8511. Engine.prototype.getStencilOperationDepthFail = function () {
  8512. return this._stencilState.stencilOpDepthFail;
  8513. };
  8514. Engine.prototype.getStencilOperationPass = function () {
  8515. return this._stencilState.stencilOpStencilDepthPass;
  8516. };
  8517. Engine.prototype.setStencilOperationFail = function (operation) {
  8518. this._stencilState.stencilOpStencilFail = operation;
  8519. };
  8520. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8521. this._stencilState.stencilOpDepthFail = operation;
  8522. };
  8523. Engine.prototype.setStencilOperationPass = function (operation) {
  8524. this._stencilState.stencilOpStencilDepthPass = operation;
  8525. };
  8526. /**
  8527. * stop executing a render loop function and remove it from the execution array
  8528. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8529. */
  8530. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8531. if (!renderFunction) {
  8532. this._activeRenderLoops = [];
  8533. return;
  8534. }
  8535. var index = this._activeRenderLoops.indexOf(renderFunction);
  8536. if (index >= 0) {
  8537. this._activeRenderLoops.splice(index, 1);
  8538. }
  8539. };
  8540. Engine.prototype._renderLoop = function () {
  8541. var shouldRender = true;
  8542. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8543. shouldRender = false;
  8544. }
  8545. if (shouldRender) {
  8546. // Start new frame
  8547. this.beginFrame();
  8548. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8549. var renderFunction = this._activeRenderLoops[index];
  8550. renderFunction();
  8551. }
  8552. // Present
  8553. this.endFrame();
  8554. }
  8555. if (this._activeRenderLoops.length > 0) {
  8556. // Register new frame
  8557. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8558. }
  8559. else {
  8560. this._renderingQueueLaunched = false;
  8561. }
  8562. };
  8563. /**
  8564. * Register and execute a render loop. The engine can have more than one render function.
  8565. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8566. * @example
  8567. * engine.runRenderLoop(function () {
  8568. * scene.render()
  8569. * })
  8570. */
  8571. Engine.prototype.runRenderLoop = function (renderFunction) {
  8572. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8573. return;
  8574. }
  8575. this._activeRenderLoops.push(renderFunction);
  8576. if (!this._renderingQueueLaunched) {
  8577. this._renderingQueueLaunched = true;
  8578. this._bindedRenderFunction = this._renderLoop.bind(this);
  8579. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8580. }
  8581. };
  8582. /**
  8583. * Toggle full screen mode.
  8584. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8585. * @param {any} options - an options object to be sent to the requestFullscreen function
  8586. */
  8587. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8588. if (this.isFullscreen) {
  8589. BABYLON.Tools.ExitFullscreen();
  8590. }
  8591. else {
  8592. this._pointerLockRequested = requestPointerLock;
  8593. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8594. }
  8595. };
  8596. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8597. if (stencil === void 0) { stencil = false; }
  8598. this.applyStates();
  8599. var mode = 0;
  8600. if (backBuffer && color) {
  8601. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8602. mode |= this._gl.COLOR_BUFFER_BIT;
  8603. }
  8604. if (depth) {
  8605. this._gl.clearDepth(1.0);
  8606. mode |= this._gl.DEPTH_BUFFER_BIT;
  8607. }
  8608. if (stencil) {
  8609. this._gl.clearStencil(0);
  8610. mode |= this._gl.STENCIL_BUFFER_BIT;
  8611. }
  8612. this._gl.clear(mode);
  8613. };
  8614. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8615. var gl = this._gl;
  8616. // Save state
  8617. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8618. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8619. // Change state
  8620. gl.enable(gl.SCISSOR_TEST);
  8621. gl.scissor(x, y, width, height);
  8622. // Clear
  8623. this.clear(clearColor, true, true, true);
  8624. // Restore state
  8625. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8626. if (curScissor === true) {
  8627. gl.enable(gl.SCISSOR_TEST);
  8628. }
  8629. else {
  8630. gl.disable(gl.SCISSOR_TEST);
  8631. }
  8632. };
  8633. /**
  8634. * Set the WebGL's viewport
  8635. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8636. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8637. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8638. */
  8639. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8640. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8641. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8642. var x = viewport.x || 0;
  8643. var y = viewport.y || 0;
  8644. this._cachedViewport = viewport;
  8645. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8646. };
  8647. /**
  8648. * Directly set the WebGL Viewport
  8649. * The x, y, width & height are directly passed to the WebGL call
  8650. * @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.
  8651. */
  8652. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8653. var currentViewport = this._cachedViewport;
  8654. this._cachedViewport = null;
  8655. this._gl.viewport(x, y, width, height);
  8656. return currentViewport;
  8657. };
  8658. Engine.prototype.beginFrame = function () {
  8659. this._measureFps();
  8660. };
  8661. Engine.prototype.endFrame = function () {
  8662. //force a flush in case we are using a bad OS.
  8663. if (this._badOS) {
  8664. this.flushFramebuffer();
  8665. }
  8666. //submit frame to the vr device, if enabled
  8667. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8668. this._vrDisplayEnabled.submitFrame();
  8669. }
  8670. };
  8671. /**
  8672. * resize the view according to the canvas' size.
  8673. * @example
  8674. * window.addEventListener("resize", function () {
  8675. * engine.resize();
  8676. * });
  8677. */
  8678. Engine.prototype.resize = function () {
  8679. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8680. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8681. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8682. };
  8683. /**
  8684. * force a specific size of the canvas
  8685. * @param {number} width - the new canvas' width
  8686. * @param {number} height - the new canvas' height
  8687. */
  8688. Engine.prototype.setSize = function (width, height) {
  8689. this._renderingCanvas.width = width;
  8690. this._renderingCanvas.height = height;
  8691. for (var index = 0; index < this.scenes.length; index++) {
  8692. var scene = this.scenes[index];
  8693. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8694. var cam = scene.cameras[camIndex];
  8695. cam._currentRenderId = 0;
  8696. }
  8697. }
  8698. };
  8699. //WebVR functions
  8700. Engine.prototype.initWebVR = function () {
  8701. if (!this.vrDisplaysPromise) {
  8702. this._getVRDisplays();
  8703. }
  8704. };
  8705. Engine.prototype.enableVR = function (vrDevice) {
  8706. this._vrDisplayEnabled = vrDevice;
  8707. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8708. };
  8709. Engine.prototype.disableVR = function () {
  8710. if (this._vrDisplayEnabled) {
  8711. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8712. }
  8713. };
  8714. Engine.prototype._getVRDisplays = function () {
  8715. var _this = this;
  8716. var getWebVRDevices = function (devices) {
  8717. var size = devices.length;
  8718. var i = 0;
  8719. _this._vrDisplays = devices.filter(function (device) {
  8720. return devices[i] instanceof VRDisplay;
  8721. });
  8722. return _this._vrDisplays;
  8723. };
  8724. //using a key due to typescript
  8725. if (navigator.getVRDisplays) {
  8726. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8727. }
  8728. };
  8729. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8730. this._currentRenderTarget = texture;
  8731. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8732. var gl = this._gl;
  8733. if (texture.isCube) {
  8734. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8735. }
  8736. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8737. this.wipeCaches();
  8738. };
  8739. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8740. if (this._currentFramebuffer !== framebuffer) {
  8741. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8742. this._currentFramebuffer = framebuffer;
  8743. }
  8744. };
  8745. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  8746. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8747. this._currentRenderTarget = null;
  8748. // If MSAA, we need to bitblt back to main texture
  8749. var gl = this._gl;
  8750. if (texture._MSAAFramebuffer) {
  8751. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8752. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8753. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8754. }
  8755. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8756. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8757. gl.generateMipmap(gl.TEXTURE_2D);
  8758. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8759. }
  8760. this.bindUnboundFramebuffer(null);
  8761. };
  8762. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8763. if (texture.generateMipMaps) {
  8764. var gl = this._gl;
  8765. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8766. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8767. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8768. }
  8769. };
  8770. Engine.prototype.flushFramebuffer = function () {
  8771. this._gl.flush();
  8772. };
  8773. Engine.prototype.restoreDefaultFramebuffer = function () {
  8774. this._currentRenderTarget = null;
  8775. this.bindUnboundFramebuffer(null);
  8776. this.setViewport(this._cachedViewport);
  8777. this.wipeCaches();
  8778. };
  8779. // VBOs
  8780. Engine.prototype._resetVertexBufferBinding = function () {
  8781. this.bindArrayBuffer(null);
  8782. this._cachedVertexBuffers = null;
  8783. };
  8784. Engine.prototype.createVertexBuffer = function (vertices) {
  8785. var vbo = this._gl.createBuffer();
  8786. this.bindArrayBuffer(vbo);
  8787. if (vertices instanceof Float32Array) {
  8788. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8789. }
  8790. else {
  8791. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8792. }
  8793. this._resetVertexBufferBinding();
  8794. vbo.references = 1;
  8795. return vbo;
  8796. };
  8797. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8798. var vbo = this._gl.createBuffer();
  8799. this.bindArrayBuffer(vbo);
  8800. if (vertices instanceof Float32Array) {
  8801. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8802. }
  8803. else {
  8804. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8805. }
  8806. this._resetVertexBufferBinding();
  8807. vbo.references = 1;
  8808. return vbo;
  8809. };
  8810. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8811. this.bindArrayBuffer(vertexBuffer);
  8812. if (offset === undefined) {
  8813. offset = 0;
  8814. }
  8815. if (count === undefined) {
  8816. if (vertices instanceof Float32Array) {
  8817. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8818. }
  8819. else {
  8820. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8821. }
  8822. }
  8823. else {
  8824. if (vertices instanceof Float32Array) {
  8825. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8826. }
  8827. else {
  8828. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8829. }
  8830. }
  8831. this._resetVertexBufferBinding();
  8832. };
  8833. Engine.prototype._resetIndexBufferBinding = function () {
  8834. this.bindIndexBuffer(null);
  8835. this._cachedIndexBuffer = null;
  8836. };
  8837. Engine.prototype.createIndexBuffer = function (indices) {
  8838. var vbo = this._gl.createBuffer();
  8839. this.bindIndexBuffer(vbo);
  8840. // Check for 32 bits indices
  8841. var arrayBuffer;
  8842. var need32Bits = false;
  8843. if (indices instanceof Uint16Array) {
  8844. arrayBuffer = indices;
  8845. }
  8846. else {
  8847. //check 32 bit support
  8848. if (this._caps.uintIndices) {
  8849. if (indices instanceof Uint32Array) {
  8850. arrayBuffer = indices;
  8851. need32Bits = true;
  8852. }
  8853. else {
  8854. //number[] or Int32Array, check if 32 bit is necessary
  8855. for (var index = 0; index < indices.length; index++) {
  8856. if (indices[index] > 65535) {
  8857. need32Bits = true;
  8858. break;
  8859. }
  8860. }
  8861. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8862. }
  8863. }
  8864. else {
  8865. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8866. arrayBuffer = new Uint16Array(indices);
  8867. }
  8868. }
  8869. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8870. this._resetIndexBufferBinding();
  8871. vbo.references = 1;
  8872. vbo.is32Bits = need32Bits;
  8873. return vbo;
  8874. };
  8875. Engine.prototype.bindArrayBuffer = function (buffer) {
  8876. if (!this._vaoRecordInProgress) {
  8877. this._unBindVertexArrayObject();
  8878. }
  8879. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8880. };
  8881. Engine.prototype.bindIndexBuffer = function (buffer) {
  8882. if (!this._vaoRecordInProgress) {
  8883. this._unBindVertexArrayObject();
  8884. }
  8885. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8886. };
  8887. Engine.prototype.bindBuffer = function (buffer, target) {
  8888. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8889. this._gl.bindBuffer(target, buffer);
  8890. this._currentBoundBuffer[target] = buffer;
  8891. }
  8892. };
  8893. Engine.prototype.updateArrayBuffer = function (data) {
  8894. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8895. };
  8896. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8897. var pointer = this._currentBufferPointers[indx];
  8898. var changed = false;
  8899. if (!pointer) {
  8900. changed = true;
  8901. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8902. }
  8903. else {
  8904. if (pointer.buffer !== buffer) {
  8905. pointer.buffer = buffer;
  8906. changed = true;
  8907. }
  8908. if (pointer.size !== size) {
  8909. pointer.size = size;
  8910. changed = true;
  8911. }
  8912. if (pointer.type !== type) {
  8913. pointer.type = type;
  8914. changed = true;
  8915. }
  8916. if (pointer.normalized !== normalized) {
  8917. pointer.normalized = normalized;
  8918. changed = true;
  8919. }
  8920. if (pointer.stride !== stride) {
  8921. pointer.stride = stride;
  8922. changed = true;
  8923. }
  8924. if (pointer.offset !== offset) {
  8925. pointer.offset = offset;
  8926. changed = true;
  8927. }
  8928. }
  8929. if (changed || this._vaoRecordInProgress) {
  8930. this.bindArrayBuffer(buffer);
  8931. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8932. }
  8933. };
  8934. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8935. if (indexBuffer == null) {
  8936. return;
  8937. }
  8938. if (this._cachedIndexBuffer !== indexBuffer) {
  8939. this._cachedIndexBuffer = indexBuffer;
  8940. this.bindIndexBuffer(indexBuffer);
  8941. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8942. }
  8943. };
  8944. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8945. var attributes = effect.getAttributesNames();
  8946. if (!this._vaoRecordInProgress) {
  8947. this._unBindVertexArrayObject();
  8948. }
  8949. this.unbindAllAttributes();
  8950. for (var index = 0; index < attributes.length; index++) {
  8951. var order = effect.getAttributeLocation(index);
  8952. if (order >= 0) {
  8953. var vertexBuffer = vertexBuffers[attributes[index]];
  8954. if (!vertexBuffer) {
  8955. continue;
  8956. }
  8957. this._gl.enableVertexAttribArray(order);
  8958. if (!this._vaoRecordInProgress) {
  8959. this._vertexAttribArraysEnabled[order] = true;
  8960. }
  8961. var buffer = vertexBuffer.getBuffer();
  8962. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8963. if (vertexBuffer.getIsInstanced()) {
  8964. this._gl.vertexAttribDivisor(order, 1);
  8965. if (!this._vaoRecordInProgress) {
  8966. this._currentInstanceLocations.push(order);
  8967. this._currentInstanceBuffers.push(buffer);
  8968. }
  8969. }
  8970. }
  8971. }
  8972. };
  8973. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8974. var vao = this._gl.createVertexArray();
  8975. this._vaoRecordInProgress = true;
  8976. this._gl.bindVertexArray(vao);
  8977. this._mustWipeVertexAttributes = true;
  8978. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8979. this.bindIndexBuffer(indexBuffer);
  8980. this._vaoRecordInProgress = false;
  8981. this._gl.bindVertexArray(null);
  8982. return vao;
  8983. };
  8984. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8985. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8986. this._cachedVertexArrayObject = vertexArrayObject;
  8987. this._gl.bindVertexArray(vertexArrayObject);
  8988. this._cachedVertexBuffers = null;
  8989. this._cachedIndexBuffer = null;
  8990. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8991. this._mustWipeVertexAttributes = true;
  8992. }
  8993. };
  8994. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8995. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8996. this._cachedVertexBuffers = vertexBuffer;
  8997. this._cachedEffectForVertexBuffers = effect;
  8998. var attributesCount = effect.getAttributesCount();
  8999. this._unBindVertexArrayObject();
  9000. this.unbindAllAttributes();
  9001. var offset = 0;
  9002. for (var index = 0; index < attributesCount; index++) {
  9003. if (index < vertexDeclaration.length) {
  9004. var order = effect.getAttributeLocation(index);
  9005. if (order >= 0) {
  9006. this._gl.enableVertexAttribArray(order);
  9007. this._vertexAttribArraysEnabled[order] = true;
  9008. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9009. }
  9010. offset += vertexDeclaration[index] * 4;
  9011. }
  9012. }
  9013. }
  9014. this._bindIndexBufferWithCache(indexBuffer);
  9015. };
  9016. Engine.prototype._unBindVertexArrayObject = function () {
  9017. if (!this._cachedVertexArrayObject) {
  9018. return;
  9019. }
  9020. this._cachedVertexArrayObject = null;
  9021. this._gl.bindVertexArray(null);
  9022. };
  9023. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9024. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9025. this._cachedVertexBuffers = vertexBuffers;
  9026. this._cachedEffectForVertexBuffers = effect;
  9027. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9028. }
  9029. this._bindIndexBufferWithCache(indexBuffer);
  9030. };
  9031. Engine.prototype.unbindInstanceAttributes = function () {
  9032. var boundBuffer;
  9033. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9034. var instancesBuffer = this._currentInstanceBuffers[i];
  9035. if (boundBuffer != instancesBuffer) {
  9036. boundBuffer = instancesBuffer;
  9037. this.bindArrayBuffer(instancesBuffer);
  9038. }
  9039. var offsetLocation = this._currentInstanceLocations[i];
  9040. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9041. }
  9042. this._currentInstanceBuffers.length = 0;
  9043. this._currentInstanceLocations.length = 0;
  9044. };
  9045. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9046. this._gl.deleteVertexArray(vao);
  9047. };
  9048. Engine.prototype._releaseBuffer = function (buffer) {
  9049. buffer.references--;
  9050. if (buffer.references === 0) {
  9051. this._gl.deleteBuffer(buffer);
  9052. return true;
  9053. }
  9054. return false;
  9055. };
  9056. Engine.prototype.createInstancesBuffer = function (capacity) {
  9057. var buffer = this._gl.createBuffer();
  9058. buffer.capacity = capacity;
  9059. this.bindArrayBuffer(buffer);
  9060. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9061. return buffer;
  9062. };
  9063. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9064. this._gl.deleteBuffer(buffer);
  9065. };
  9066. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9067. this.bindArrayBuffer(instancesBuffer);
  9068. if (data) {
  9069. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9070. }
  9071. if (offsetLocations[0].index !== undefined) {
  9072. var stride = 0;
  9073. for (var i = 0; i < offsetLocations.length; i++) {
  9074. var ai = offsetLocations[i];
  9075. stride += ai.attributeSize * 4;
  9076. }
  9077. for (var i = 0; i < offsetLocations.length; i++) {
  9078. var ai = offsetLocations[i];
  9079. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9080. this._gl.enableVertexAttribArray(ai.index);
  9081. this._vertexAttribArraysEnabled[ai.index] = true;
  9082. }
  9083. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9084. this._gl.vertexAttribDivisor(ai.index, 1);
  9085. this._currentInstanceLocations.push(ai.index);
  9086. this._currentInstanceBuffers.push(instancesBuffer);
  9087. }
  9088. }
  9089. else {
  9090. for (var index = 0; index < 4; index++) {
  9091. var offsetLocation = offsetLocations[index];
  9092. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9093. this._gl.enableVertexAttribArray(offsetLocation);
  9094. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9095. }
  9096. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9097. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9098. this._currentInstanceLocations.push(offsetLocation);
  9099. this._currentInstanceBuffers.push(instancesBuffer);
  9100. }
  9101. }
  9102. };
  9103. Engine.prototype.applyStates = function () {
  9104. this._depthCullingState.apply(this._gl);
  9105. this._stencilState.apply(this._gl);
  9106. this._alphaState.apply(this._gl);
  9107. };
  9108. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9109. // Apply states
  9110. this.applyStates();
  9111. this._drawCalls.addCount(1, false);
  9112. // Render
  9113. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9114. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9115. if (instancesCount) {
  9116. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9117. return;
  9118. }
  9119. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9120. };
  9121. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9122. // Apply states
  9123. this.applyStates();
  9124. this._drawCalls.addCount(1, false);
  9125. if (instancesCount) {
  9126. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9127. return;
  9128. }
  9129. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9130. };
  9131. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9132. // Apply states
  9133. this.applyStates();
  9134. this._drawCalls.addCount(1, false);
  9135. if (instancesCount) {
  9136. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9137. return;
  9138. }
  9139. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9140. };
  9141. // Shaders
  9142. Engine.prototype._releaseEffect = function (effect) {
  9143. if (this._compiledEffects[effect._key]) {
  9144. delete this._compiledEffects[effect._key];
  9145. if (effect.getProgram()) {
  9146. this._gl.deleteProgram(effect.getProgram());
  9147. }
  9148. }
  9149. };
  9150. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9151. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9152. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9153. var name = vertex + "+" + fragment + "@" + defines;
  9154. if (this._compiledEffects[name]) {
  9155. return this._compiledEffects[name];
  9156. }
  9157. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9158. effect._key = name;
  9159. this._compiledEffects[name] = effect;
  9160. return effect;
  9161. };
  9162. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9163. if (uniformsNames === void 0) { uniformsNames = []; }
  9164. if (samplers === void 0) { samplers = []; }
  9165. if (defines === void 0) { defines = ""; }
  9166. return this.createEffect({
  9167. vertex: "particles",
  9168. fragmentElement: fragmentName
  9169. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9170. };
  9171. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9172. context = context || this._gl;
  9173. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9174. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9175. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9176. var shaderProgram = context.createProgram();
  9177. context.attachShader(shaderProgram, vertexShader);
  9178. context.attachShader(shaderProgram, fragmentShader);
  9179. context.linkProgram(shaderProgram);
  9180. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9181. if (!linked) {
  9182. var error = context.getProgramInfoLog(shaderProgram);
  9183. if (error) {
  9184. throw new Error(error);
  9185. }
  9186. }
  9187. context.deleteShader(vertexShader);
  9188. context.deleteShader(fragmentShader);
  9189. return shaderProgram;
  9190. };
  9191. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9192. var results = [];
  9193. for (var index = 0; index < uniformsNames.length; index++) {
  9194. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9195. }
  9196. return results;
  9197. };
  9198. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9199. var results = [];
  9200. for (var index = 0; index < attributesNames.length; index++) {
  9201. try {
  9202. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9203. }
  9204. catch (e) {
  9205. results.push(-1);
  9206. }
  9207. }
  9208. return results;
  9209. };
  9210. Engine.prototype.enableEffect = function (effect) {
  9211. // Use program
  9212. this.setProgram(effect.getProgram());
  9213. this._currentEffect = effect;
  9214. if (effect.onBind) {
  9215. effect.onBind(effect);
  9216. }
  9217. };
  9218. Engine.prototype.setIntArray = function (uniform, array) {
  9219. if (!uniform)
  9220. return;
  9221. this._gl.uniform1iv(uniform, array);
  9222. };
  9223. Engine.prototype.setIntArray2 = function (uniform, array) {
  9224. if (!uniform || array.length % 2 !== 0)
  9225. return;
  9226. this._gl.uniform2iv(uniform, array);
  9227. };
  9228. Engine.prototype.setIntArray3 = function (uniform, array) {
  9229. if (!uniform || array.length % 3 !== 0)
  9230. return;
  9231. this._gl.uniform3iv(uniform, array);
  9232. };
  9233. Engine.prototype.setIntArray4 = function (uniform, array) {
  9234. if (!uniform || array.length % 4 !== 0)
  9235. return;
  9236. this._gl.uniform4iv(uniform, array);
  9237. };
  9238. Engine.prototype.setFloatArray = function (uniform, array) {
  9239. if (!uniform)
  9240. return;
  9241. this._gl.uniform1fv(uniform, array);
  9242. };
  9243. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9244. if (!uniform || array.length % 2 !== 0)
  9245. return;
  9246. this._gl.uniform2fv(uniform, array);
  9247. };
  9248. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9249. if (!uniform || array.length % 3 !== 0)
  9250. return;
  9251. this._gl.uniform3fv(uniform, array);
  9252. };
  9253. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9254. if (!uniform || array.length % 4 !== 0)
  9255. return;
  9256. this._gl.uniform4fv(uniform, array);
  9257. };
  9258. Engine.prototype.setArray = function (uniform, array) {
  9259. if (!uniform)
  9260. return;
  9261. this._gl.uniform1fv(uniform, array);
  9262. };
  9263. Engine.prototype.setArray2 = function (uniform, array) {
  9264. if (!uniform || array.length % 2 !== 0)
  9265. return;
  9266. this._gl.uniform2fv(uniform, array);
  9267. };
  9268. Engine.prototype.setArray3 = function (uniform, array) {
  9269. if (!uniform || array.length % 3 !== 0)
  9270. return;
  9271. this._gl.uniform3fv(uniform, array);
  9272. };
  9273. Engine.prototype.setArray4 = function (uniform, array) {
  9274. if (!uniform || array.length % 4 !== 0)
  9275. return;
  9276. this._gl.uniform4fv(uniform, array);
  9277. };
  9278. Engine.prototype.setMatrices = function (uniform, matrices) {
  9279. if (!uniform)
  9280. return;
  9281. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9282. };
  9283. Engine.prototype.setMatrix = function (uniform, matrix) {
  9284. if (!uniform)
  9285. return;
  9286. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9287. };
  9288. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9289. if (!uniform)
  9290. return;
  9291. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9292. };
  9293. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9294. if (!uniform)
  9295. return;
  9296. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9297. };
  9298. Engine.prototype.setFloat = function (uniform, value) {
  9299. if (!uniform)
  9300. return;
  9301. this._gl.uniform1f(uniform, value);
  9302. };
  9303. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9304. if (!uniform)
  9305. return;
  9306. this._gl.uniform2f(uniform, x, y);
  9307. };
  9308. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9309. if (!uniform)
  9310. return;
  9311. this._gl.uniform3f(uniform, x, y, z);
  9312. };
  9313. Engine.prototype.setBool = function (uniform, bool) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform1i(uniform, bool);
  9317. };
  9318. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9319. if (!uniform)
  9320. return;
  9321. this._gl.uniform4f(uniform, x, y, z, w);
  9322. };
  9323. Engine.prototype.setColor3 = function (uniform, color3) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9327. };
  9328. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9329. if (!uniform)
  9330. return;
  9331. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9332. };
  9333. // States
  9334. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9335. if (zOffset === void 0) { zOffset = 0; }
  9336. if (reverseSide === void 0) { reverseSide = false; }
  9337. // Culling
  9338. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9339. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9340. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9341. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9342. if (culling) {
  9343. this._depthCullingState.cullFace = cullFace;
  9344. this._depthCullingState.cull = true;
  9345. }
  9346. else {
  9347. this._depthCullingState.cull = false;
  9348. }
  9349. }
  9350. // Z offset
  9351. this._depthCullingState.zOffset = zOffset;
  9352. };
  9353. Engine.prototype.setDepthBuffer = function (enable) {
  9354. this._depthCullingState.depthTest = enable;
  9355. };
  9356. Engine.prototype.getDepthWrite = function () {
  9357. return this._depthCullingState.depthMask;
  9358. };
  9359. Engine.prototype.setDepthWrite = function (enable) {
  9360. this._depthCullingState.depthMask = enable;
  9361. };
  9362. Engine.prototype.setColorWrite = function (enable) {
  9363. this._gl.colorMask(enable, enable, enable, enable);
  9364. };
  9365. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9366. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9367. if (this._alphaMode === mode) {
  9368. return;
  9369. }
  9370. switch (mode) {
  9371. case Engine.ALPHA_DISABLE:
  9372. this._alphaState.alphaBlend = false;
  9373. break;
  9374. case Engine.ALPHA_PREMULTIPLIED:
  9375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9376. this._alphaState.alphaBlend = true;
  9377. break;
  9378. case Engine.ALPHA_COMBINE:
  9379. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9380. this._alphaState.alphaBlend = true;
  9381. break;
  9382. case Engine.ALPHA_ONEONE:
  9383. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9384. this._alphaState.alphaBlend = true;
  9385. break;
  9386. case Engine.ALPHA_ADD:
  9387. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9388. this._alphaState.alphaBlend = true;
  9389. break;
  9390. case Engine.ALPHA_SUBTRACT:
  9391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9392. this._alphaState.alphaBlend = true;
  9393. break;
  9394. case Engine.ALPHA_MULTIPLY:
  9395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9396. this._alphaState.alphaBlend = true;
  9397. break;
  9398. case Engine.ALPHA_MAXIMIZED:
  9399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9400. this._alphaState.alphaBlend = true;
  9401. break;
  9402. }
  9403. if (!noDepthWriteChange) {
  9404. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9405. }
  9406. this._alphaMode = mode;
  9407. };
  9408. Engine.prototype.getAlphaMode = function () {
  9409. return this._alphaMode;
  9410. };
  9411. Engine.prototype.setAlphaTesting = function (enable) {
  9412. this._alphaTest = enable;
  9413. };
  9414. Engine.prototype.getAlphaTesting = function () {
  9415. return this._alphaTest;
  9416. };
  9417. // Textures
  9418. Engine.prototype.wipeCaches = function () {
  9419. this.resetTextureCache();
  9420. this._currentEffect = null;
  9421. this._stencilState.reset();
  9422. this._depthCullingState.reset();
  9423. this.setDepthFunctionToLessOrEqual();
  9424. this._alphaState.reset();
  9425. this._cachedVertexBuffers = null;
  9426. this._cachedIndexBuffer = null;
  9427. this._cachedEffectForVertexBuffers = null;
  9428. this._unBindVertexArrayObject();
  9429. this.bindIndexBuffer(null);
  9430. this.bindArrayBuffer(null);
  9431. };
  9432. /**
  9433. * Set the compressed texture format to use, based on the formats you have, and the formats
  9434. * supported by the hardware / browser.
  9435. *
  9436. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9437. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9438. * to API arguments needed to compressed textures. This puts the burden on the container
  9439. * generator to house the arcane code for determining these for current & future formats.
  9440. *
  9441. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9442. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9443. *
  9444. * Note: The result of this call is not taken into account when a texture is base64.
  9445. *
  9446. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9447. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9448. *
  9449. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9450. * @returns The extension selected.
  9451. */
  9452. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9453. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9454. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9455. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9456. return this._textureFormatInUse = this._texturesSupported[i];
  9457. }
  9458. }
  9459. }
  9460. // actively set format to nothing, to allow this to be called more than once
  9461. // and possibly fail the 2nd time
  9462. return this._textureFormatInUse = null;
  9463. };
  9464. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9465. var _this = this;
  9466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9467. if (onLoad === void 0) { onLoad = null; }
  9468. if (onError === void 0) { onError = null; }
  9469. if (buffer === void 0) { buffer = null; }
  9470. var texture = fallBack ? fallBack : this._gl.createTexture();
  9471. var extension;
  9472. var isKTX = false;
  9473. var fromData = false;
  9474. var url = String(urlArg);
  9475. if (url.substr(0, 5) === "data:") {
  9476. fromData = true;
  9477. }
  9478. if (!fromData) {
  9479. var lastDot = url.lastIndexOf('.');
  9480. extension = url.substring(lastDot).toLowerCase();
  9481. if (this._textureFormatInUse && !fromData && !fallBack) {
  9482. extension = this._textureFormatInUse;
  9483. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9484. isKTX = true;
  9485. }
  9486. }
  9487. else {
  9488. var oldUrl = url;
  9489. fromData = oldUrl.split(':');
  9490. url = oldUrl;
  9491. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9492. }
  9493. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9494. var isTGA = (extension === ".tga");
  9495. scene._addPendingData(texture);
  9496. texture.url = url;
  9497. texture.noMipmap = noMipmap;
  9498. texture.references = 1;
  9499. texture.samplingMode = samplingMode;
  9500. texture.onLoadedCallbacks = [];
  9501. if (onLoad) {
  9502. texture.onLoadedCallbacks.push(onLoad);
  9503. }
  9504. if (!fallBack)
  9505. this._loadedTexturesCache.push(texture);
  9506. var onerror = function () {
  9507. scene._removePendingData(texture);
  9508. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9509. if (isKTX) {
  9510. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9511. }
  9512. else if (onError) {
  9513. onError();
  9514. }
  9515. };
  9516. var callback;
  9517. if (isKTX || isTGA || isDDS) {
  9518. if (isKTX) {
  9519. callback = function (data) {
  9520. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9521. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9522. ktx.uploadLevels(_this._gl, !noMipmap);
  9523. }, samplingMode);
  9524. };
  9525. }
  9526. else if (isTGA) {
  9527. callback = function (arrayBuffer) {
  9528. var data = new Uint8Array(arrayBuffer);
  9529. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9530. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9531. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9532. }, samplingMode);
  9533. };
  9534. }
  9535. else if (isDDS) {
  9536. callback = function (data) {
  9537. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9538. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9539. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9540. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9541. }, samplingMode);
  9542. };
  9543. }
  9544. if (!(fromData instanceof Array))
  9545. BABYLON.Tools.LoadFile(url, function (data) {
  9546. callback(data);
  9547. }, null, scene.database, true, onerror);
  9548. else
  9549. callback(buffer);
  9550. }
  9551. else {
  9552. var onload = function (img) {
  9553. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9554. var isPot = (img.width === potWidth && img.height === potHeight);
  9555. if (!isPot) {
  9556. _this._prepareWorkingCanvas();
  9557. _this._workingCanvas.width = potWidth;
  9558. _this._workingCanvas.height = potHeight;
  9559. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9560. _this._workingContext.imageSmoothingEnabled = false;
  9561. _this._workingContext.mozImageSmoothingEnabled = false;
  9562. _this._workingContext.oImageSmoothingEnabled = false;
  9563. _this._workingContext.webkitImageSmoothingEnabled = false;
  9564. _this._workingContext.msImageSmoothingEnabled = false;
  9565. }
  9566. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9567. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9568. _this._workingContext.imageSmoothingEnabled = true;
  9569. _this._workingContext.mozImageSmoothingEnabled = true;
  9570. _this._workingContext.oImageSmoothingEnabled = true;
  9571. _this._workingContext.webkitImageSmoothingEnabled = true;
  9572. _this._workingContext.msImageSmoothingEnabled = true;
  9573. }
  9574. }
  9575. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9576. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9577. }, samplingMode);
  9578. };
  9579. if (!(fromData instanceof Array))
  9580. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9581. else
  9582. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9583. }
  9584. return texture;
  9585. };
  9586. Engine.prototype._getInternalFormat = function (format) {
  9587. var internalFormat = this._gl.RGBA;
  9588. switch (format) {
  9589. case Engine.TEXTUREFORMAT_ALPHA:
  9590. internalFormat = this._gl.ALPHA;
  9591. break;
  9592. case Engine.TEXTUREFORMAT_LUMINANCE:
  9593. internalFormat = this._gl.LUMINANCE;
  9594. break;
  9595. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9596. internalFormat = this._gl.LUMINANCE_ALPHA;
  9597. break;
  9598. case Engine.TEXTUREFORMAT_RGB:
  9599. internalFormat = this._gl.RGB;
  9600. break;
  9601. case Engine.TEXTUREFORMAT_RGBA:
  9602. internalFormat = this._gl.RGBA;
  9603. break;
  9604. }
  9605. return internalFormat;
  9606. };
  9607. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9608. if (compression === void 0) { compression = null; }
  9609. var internalFormat = this._getInternalFormat(format);
  9610. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9611. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9612. if (texture._width % 4 !== 0) {
  9613. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9614. }
  9615. if (compression) {
  9616. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9617. }
  9618. else {
  9619. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9620. }
  9621. if (texture.generateMipMaps) {
  9622. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9623. }
  9624. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9625. this.resetTextureCache();
  9626. texture.isReady = true;
  9627. };
  9628. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9629. if (compression === void 0) { compression = null; }
  9630. var texture = this._gl.createTexture();
  9631. texture._baseWidth = width;
  9632. texture._baseHeight = height;
  9633. texture._width = width;
  9634. texture._height = height;
  9635. texture.references = 1;
  9636. this.updateRawTexture(texture, data, format, invertY, compression);
  9637. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9638. // Filters
  9639. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9641. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9642. if (generateMipMaps) {
  9643. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9644. }
  9645. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9646. texture.samplingMode = samplingMode;
  9647. this._loadedTexturesCache.push(texture);
  9648. return texture;
  9649. };
  9650. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9651. var texture = this._gl.createTexture();
  9652. texture._baseWidth = width;
  9653. texture._baseHeight = height;
  9654. if (generateMipMaps) {
  9655. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9656. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9657. }
  9658. this.resetTextureCache();
  9659. texture._width = width;
  9660. texture._height = height;
  9661. texture.isReady = false;
  9662. texture.generateMipMaps = generateMipMaps;
  9663. texture.references = 1;
  9664. texture.samplingMode = samplingMode;
  9665. this.updateTextureSamplingMode(samplingMode, texture);
  9666. this._loadedTexturesCache.push(texture);
  9667. return texture;
  9668. };
  9669. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9670. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9671. if (texture.isCube) {
  9672. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9673. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9674. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9675. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9676. }
  9677. else {
  9678. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9679. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9680. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9681. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9682. }
  9683. texture.samplingMode = samplingMode;
  9684. };
  9685. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9686. if (premulAlpha === void 0) { premulAlpha = false; }
  9687. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9688. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9689. if (premulAlpha) {
  9690. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9691. }
  9692. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9693. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9694. if (texture.generateMipMaps) {
  9695. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9696. }
  9697. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9698. if (premulAlpha) {
  9699. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9700. }
  9701. this.resetTextureCache();
  9702. texture.isReady = true;
  9703. };
  9704. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9705. if (texture._isDisabled) {
  9706. return;
  9707. }
  9708. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9709. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9710. try {
  9711. // Testing video texture support
  9712. if (this._videoTextureSupported === undefined) {
  9713. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9714. if (this._gl.getError() !== 0) {
  9715. this._videoTextureSupported = false;
  9716. }
  9717. else {
  9718. this._videoTextureSupported = true;
  9719. }
  9720. }
  9721. // Copy video through the current working canvas if video texture is not supported
  9722. if (!this._videoTextureSupported) {
  9723. if (!texture._workingCanvas) {
  9724. texture._workingCanvas = document.createElement("canvas");
  9725. texture._workingContext = texture._workingCanvas.getContext("2d");
  9726. texture._workingCanvas.width = texture._width;
  9727. texture._workingCanvas.height = texture._height;
  9728. }
  9729. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9730. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9731. }
  9732. else {
  9733. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9734. }
  9735. if (texture.generateMipMaps) {
  9736. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9737. }
  9738. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9739. this.resetTextureCache();
  9740. texture.isReady = true;
  9741. }
  9742. catch (ex) {
  9743. // Something unexpected
  9744. // Let's disable the texture
  9745. texture._isDisabled = true;
  9746. }
  9747. };
  9748. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9749. // old version had a "generateMipMaps" arg instead of options.
  9750. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9751. // in the same way, generateDepthBuffer is defaulted to true
  9752. var generateMipMaps = false;
  9753. var generateDepthBuffer = true;
  9754. var generateStencilBuffer = false;
  9755. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9756. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9757. if (options !== undefined) {
  9758. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9759. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9760. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9761. type = options.type === undefined ? type : options.type;
  9762. if (options.samplingMode !== undefined) {
  9763. samplingMode = options.samplingMode;
  9764. }
  9765. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9766. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9767. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9768. }
  9769. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9770. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9771. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9772. }
  9773. }
  9774. var gl = this._gl;
  9775. var texture = gl.createTexture();
  9776. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9777. var width = size.width || size;
  9778. var height = size.height || size;
  9779. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9780. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9781. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9782. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9783. }
  9784. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9788. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9789. // Create the framebuffer
  9790. var framebuffer = gl.createFramebuffer();
  9791. this.bindUnboundFramebuffer(framebuffer);
  9792. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9793. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9794. if (generateMipMaps) {
  9795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9796. }
  9797. // Unbind
  9798. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9799. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9800. this.bindUnboundFramebuffer(null);
  9801. texture._framebuffer = framebuffer;
  9802. texture._baseWidth = width;
  9803. texture._baseHeight = height;
  9804. texture._width = width;
  9805. texture._height = height;
  9806. texture.isReady = true;
  9807. texture.samples = 1;
  9808. texture.generateMipMaps = generateMipMaps;
  9809. texture.references = 1;
  9810. texture.samplingMode = samplingMode;
  9811. texture.type = type;
  9812. texture._generateDepthBuffer = generateDepthBuffer;
  9813. texture._generateStencilBuffer = generateStencilBuffer;
  9814. this.resetTextureCache();
  9815. this._loadedTexturesCache.push(texture);
  9816. return texture;
  9817. };
  9818. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9819. if (samples === void 0) { samples = 1; }
  9820. var depthStencilBuffer = null;
  9821. var gl = this._gl;
  9822. // Create the depth/stencil buffer
  9823. if (generateStencilBuffer) {
  9824. depthStencilBuffer = gl.createRenderbuffer();
  9825. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9826. if (samples > 1) {
  9827. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9828. }
  9829. else {
  9830. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9831. }
  9832. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9833. }
  9834. else if (generateDepthBuffer) {
  9835. depthStencilBuffer = gl.createRenderbuffer();
  9836. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9837. if (samples > 1) {
  9838. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9839. }
  9840. else {
  9841. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9842. }
  9843. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9844. }
  9845. return depthStencilBuffer;
  9846. };
  9847. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9848. if (this.webGLVersion < 2) {
  9849. return 1;
  9850. }
  9851. if (texture.samples === samples) {
  9852. return samples;
  9853. }
  9854. var gl = this._gl;
  9855. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9856. // Dispose previous render buffers
  9857. if (texture._depthStencilBuffer) {
  9858. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9859. }
  9860. if (texture._MSAAFramebuffer) {
  9861. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9862. }
  9863. if (texture._MSAARenderBuffer) {
  9864. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9865. }
  9866. if (samples > 1) {
  9867. texture._MSAAFramebuffer = gl.createFramebuffer();
  9868. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9869. var colorRenderbuffer = gl.createRenderbuffer();
  9870. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9871. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9872. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9873. texture._MSAARenderBuffer = colorRenderbuffer;
  9874. }
  9875. else {
  9876. this.bindUnboundFramebuffer(texture._framebuffer);
  9877. }
  9878. texture.samples = samples;
  9879. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9880. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9881. this.bindUnboundFramebuffer(null);
  9882. return samples;
  9883. };
  9884. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9885. var gl = this._gl;
  9886. var texture = gl.createTexture();
  9887. var generateMipMaps = true;
  9888. var generateDepthBuffer = true;
  9889. var generateStencilBuffer = false;
  9890. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9891. if (options !== undefined) {
  9892. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9893. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9894. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9895. if (options.samplingMode !== undefined) {
  9896. samplingMode = options.samplingMode;
  9897. }
  9898. }
  9899. texture.isCube = true;
  9900. texture.references = 1;
  9901. texture.generateMipMaps = generateMipMaps;
  9902. texture.references = 1;
  9903. texture.samples = 1;
  9904. texture.samplingMode = samplingMode;
  9905. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9906. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9907. for (var face = 0; face < 6; face++) {
  9908. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9909. }
  9910. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9914. // Create the framebuffer
  9915. var framebuffer = gl.createFramebuffer();
  9916. this.bindUnboundFramebuffer(framebuffer);
  9917. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9918. // Mipmaps
  9919. if (texture.generateMipMaps) {
  9920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9921. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9922. }
  9923. // Unbind
  9924. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9925. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9926. this.bindUnboundFramebuffer(null);
  9927. texture._framebuffer = framebuffer;
  9928. texture._width = size;
  9929. texture._height = size;
  9930. texture.isReady = true;
  9931. this.resetTextureCache();
  9932. this._loadedTexturesCache.push(texture);
  9933. return texture;
  9934. };
  9935. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9936. var _this = this;
  9937. if (onLoad === void 0) { onLoad = null; }
  9938. if (onError === void 0) { onError = null; }
  9939. var gl = this._gl;
  9940. var texture = gl.createTexture();
  9941. texture.isCube = true;
  9942. texture.url = rootUrl;
  9943. texture.references = 1;
  9944. texture.onLoadedCallbacks = [];
  9945. var isKTX = false;
  9946. var lastDot = rootUrl.lastIndexOf('.');
  9947. var extension = rootUrl.substring(lastDot).toLowerCase();
  9948. if (this._textureFormatInUse) {
  9949. extension = this._textureFormatInUse;
  9950. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9951. isKTX = true;
  9952. }
  9953. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9954. if (isKTX) {
  9955. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9956. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9957. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9958. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9959. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9960. ktx.uploadLevels(_this._gl, !noMipmap);
  9961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9965. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9966. _this.resetTextureCache();
  9967. texture._width = ktx.pixelWidth;
  9968. texture._height = ktx.pixelHeight;
  9969. texture.isReady = true;
  9970. }, null, null, true, onError);
  9971. }
  9972. else if (isDDS) {
  9973. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9974. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9975. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9976. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9977. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9978. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9979. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9980. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9981. }
  9982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9983. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9984. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9987. _this.resetTextureCache();
  9988. texture._width = info.width;
  9989. texture._height = info.height;
  9990. texture.isReady = true;
  9991. }, null, null, true, onError);
  9992. }
  9993. else {
  9994. cascadeLoad(rootUrl, scene, function (imgs) {
  9995. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9996. var height = width;
  9997. _this._prepareWorkingCanvas();
  9998. _this._workingCanvas.width = width;
  9999. _this._workingCanvas.height = height;
  10000. var faces = [
  10001. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10002. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10003. ];
  10004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10005. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10006. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10007. for (var index = 0; index < faces.length; index++) {
  10008. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10009. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10010. }
  10011. if (!noMipmap) {
  10012. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10013. }
  10014. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10018. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10019. _this.resetTextureCache();
  10020. texture._width = width;
  10021. texture._height = height;
  10022. texture.isReady = true;
  10023. texture.onLoadedCallbacks.forEach(function (callback) {
  10024. callback();
  10025. });
  10026. if (onLoad) {
  10027. onLoad();
  10028. }
  10029. }, files, onError);
  10030. }
  10031. this._loadedTexturesCache.push(texture);
  10032. return texture;
  10033. };
  10034. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10035. texture._width = width;
  10036. texture._height = height;
  10037. texture._size = width * height;
  10038. texture._baseWidth = width;
  10039. texture._baseHeight = height;
  10040. };
  10041. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10042. var _this = this;
  10043. if (onLoad === void 0) { onLoad = null; }
  10044. if (onError === void 0) { onError = null; }
  10045. var gl = this._gl;
  10046. var texture = gl.createTexture();
  10047. scene._addPendingData(texture);
  10048. texture.isCube = true;
  10049. texture.references = 1;
  10050. texture.url = url;
  10051. var textureType = gl.UNSIGNED_BYTE;
  10052. if (type === Engine.TEXTURETYPE_FLOAT) {
  10053. textureType = gl.FLOAT;
  10054. }
  10055. var internalFormat = this._getInternalFormat(format);
  10056. var needConversion = false;
  10057. if (internalFormat === gl.RGB) {
  10058. internalFormat = gl.RGBA;
  10059. needConversion = true;
  10060. }
  10061. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10062. var width = size;
  10063. var height = width;
  10064. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10065. texture._width = width;
  10066. texture._height = height;
  10067. var onerror = function () {
  10068. scene._removePendingData(texture);
  10069. if (onError) {
  10070. onError();
  10071. }
  10072. };
  10073. var internalCallback = function (data) {
  10074. var rgbeDataArrays = callback(data);
  10075. var facesIndex = [
  10076. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10077. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10078. ];
  10079. width = texture._width;
  10080. height = texture._height;
  10081. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10082. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10083. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10084. if (mipmmapGenerator) {
  10085. var arrayTemp = [];
  10086. // Data are known to be in +X +Y +Z -X -Y -Z
  10087. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10088. arrayTemp.push(rgbeDataArrays[0]); // +X
  10089. arrayTemp.push(rgbeDataArrays[3]); // -X
  10090. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10091. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10092. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10093. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10094. var mipData = mipmmapGenerator(arrayTemp);
  10095. // mipData is order in +X -X +Y -Y +Z -Z
  10096. var mipFaces = [0, 2, 4, 1, 3, 5];
  10097. for (var level = 0; level < mipData.length; level++) {
  10098. var mipSize = width >> level;
  10099. for (var mipIndex in mipFaces) {
  10100. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10101. if (needConversion) {
  10102. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10103. }
  10104. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10105. }
  10106. }
  10107. }
  10108. else {
  10109. // Data are known to be in +X +Y +Z -X -Y -Z
  10110. for (var index = 0; index < facesIndex.length; index++) {
  10111. var faceData = rgbeDataArrays[index];
  10112. if (needConversion) {
  10113. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10114. }
  10115. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10116. }
  10117. if (!noMipmap && isPot) {
  10118. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10119. }
  10120. else {
  10121. noMipmap = true;
  10122. }
  10123. }
  10124. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10125. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10127. }
  10128. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10131. }
  10132. else {
  10133. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10134. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10135. }
  10136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10138. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10139. texture.isReady = true;
  10140. _this.resetTextureCache();
  10141. scene._removePendingData(texture);
  10142. if (onLoad) {
  10143. onLoad();
  10144. }
  10145. };
  10146. BABYLON.Tools.LoadFile(url, function (data) {
  10147. internalCallback(data);
  10148. }, onerror, scene.database, true);
  10149. return texture;
  10150. };
  10151. ;
  10152. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10153. // Create new RGBA data container.
  10154. var rgbaData;
  10155. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10156. rgbaData = new Float32Array(width * height * 4);
  10157. }
  10158. else {
  10159. rgbaData = new Uint32Array(width * height * 4);
  10160. }
  10161. // Convert each pixel.
  10162. for (var x = 0; x < width; x++) {
  10163. for (var y = 0; y < height; y++) {
  10164. var index = (y * width + x) * 3;
  10165. var newIndex = (y * width + x) * 4;
  10166. // Map Old Value to new value.
  10167. rgbaData[newIndex + 0] = rgbData[index + 0];
  10168. rgbaData[newIndex + 1] = rgbData[index + 1];
  10169. rgbaData[newIndex + 2] = rgbData[index + 2];
  10170. // Add fully opaque alpha channel.
  10171. rgbaData[newIndex + 3] = 1;
  10172. }
  10173. }
  10174. return rgbaData;
  10175. };
  10176. Engine.prototype._releaseTexture = function (texture) {
  10177. var gl = this._gl;
  10178. if (texture._framebuffer) {
  10179. gl.deleteFramebuffer(texture._framebuffer);
  10180. }
  10181. if (texture._depthStencilBuffer) {
  10182. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10183. }
  10184. if (texture._MSAAFramebuffer) {
  10185. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10186. }
  10187. if (texture._MSAARenderBuffer) {
  10188. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10189. }
  10190. gl.deleteTexture(texture);
  10191. // Unbind channels
  10192. this.unbindAllTextures();
  10193. var index = this._loadedTexturesCache.indexOf(texture);
  10194. if (index !== -1) {
  10195. this._loadedTexturesCache.splice(index, 1);
  10196. }
  10197. };
  10198. Engine.prototype.setProgram = function (program) {
  10199. if (this._currentProgram !== program) {
  10200. this._gl.useProgram(program);
  10201. this._currentProgram = program;
  10202. }
  10203. };
  10204. Engine.prototype.bindSamplers = function (effect) {
  10205. this.setProgram(effect.getProgram());
  10206. var samplers = effect.getSamplers();
  10207. for (var index = 0; index < samplers.length; index++) {
  10208. var uniform = effect.getUniform(samplers[index]);
  10209. this._gl.uniform1i(uniform, index);
  10210. }
  10211. this._currentEffect = null;
  10212. };
  10213. Engine.prototype.activateTexture = function (texture) {
  10214. if (this._activeTexture !== texture) {
  10215. this._gl.activeTexture(texture);
  10216. this._activeTexture = texture;
  10217. }
  10218. };
  10219. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10220. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10221. this._gl.bindTexture(target, texture);
  10222. this._activeTexturesCache[this._activeTexture] = texture;
  10223. }
  10224. };
  10225. Engine.prototype._bindTexture = function (channel, texture) {
  10226. if (channel < 0) {
  10227. return;
  10228. }
  10229. this.activateTexture(this._gl.TEXTURE0 + channel);
  10230. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10231. };
  10232. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10233. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10234. };
  10235. Engine.prototype.unbindAllTextures = function () {
  10236. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10237. this.activateTexture(this._gl["TEXTURE" + channel]);
  10238. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10239. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10240. }
  10241. };
  10242. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10243. if (channel < 0) {
  10244. return;
  10245. }
  10246. this._gl.uniform1i(uniform, channel);
  10247. this._setTexture(channel, texture);
  10248. };
  10249. Engine.prototype._setTexture = function (channel, texture) {
  10250. // Not ready?
  10251. if (!texture || !texture.isReady()) {
  10252. if (this._activeTexturesCache[channel] != null) {
  10253. this.activateTexture(this._gl["TEXTURE" + channel]);
  10254. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10255. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10256. }
  10257. return;
  10258. }
  10259. // Video
  10260. var alreadyActivated = false;
  10261. if (texture instanceof BABYLON.VideoTexture) {
  10262. this.activateTexture(this._gl["TEXTURE" + channel]);
  10263. alreadyActivated = true;
  10264. texture.update();
  10265. }
  10266. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10267. texture.delayLoad();
  10268. return;
  10269. }
  10270. var internalTexture = texture.getInternalTexture();
  10271. if (this._activeTexturesCache[channel] === internalTexture) {
  10272. return;
  10273. }
  10274. if (!alreadyActivated) {
  10275. this.activateTexture(this._gl["TEXTURE" + channel]);
  10276. }
  10277. if (internalTexture.isCube) {
  10278. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10279. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10280. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10281. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10282. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10283. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10284. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10285. }
  10286. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10287. }
  10288. else {
  10289. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10290. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10291. internalTexture._cachedWrapU = texture.wrapU;
  10292. switch (texture.wrapU) {
  10293. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10295. break;
  10296. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10297. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10298. break;
  10299. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10301. break;
  10302. }
  10303. }
  10304. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10305. internalTexture._cachedWrapV = texture.wrapV;
  10306. switch (texture.wrapV) {
  10307. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10308. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10309. break;
  10310. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10312. break;
  10313. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10315. break;
  10316. }
  10317. }
  10318. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10319. }
  10320. };
  10321. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10322. if (channel < 0) {
  10323. return;
  10324. }
  10325. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10326. this._textureUnits = new Int32Array(textures.length);
  10327. }
  10328. for (var i = 0; i < textures.length; i++) {
  10329. this._textureUnits[i] = channel + i;
  10330. }
  10331. this._gl.uniform1iv(uniform, this._textureUnits);
  10332. for (var index = 0; index < textures.length; index++) {
  10333. this._setTexture(channel + index, textures[index]);
  10334. }
  10335. };
  10336. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10337. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10338. var value = texture.anisotropicFilteringLevel;
  10339. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10340. value = 1;
  10341. }
  10342. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10343. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10344. texture._cachedAnisotropicFilteringLevel = value;
  10345. }
  10346. };
  10347. Engine.prototype.readPixels = function (x, y, width, height) {
  10348. var data = new Uint8Array(height * width * 4);
  10349. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10350. return data;
  10351. };
  10352. /**
  10353. * Add an externaly attached data from its key.
  10354. * This method call will fail and return false, if such key already exists.
  10355. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10356. * @param key the unique key that identifies the data
  10357. * @param data the data object to associate to the key for this Engine instance
  10358. * @return true if no such key were already present and the data was added successfully, false otherwise
  10359. */
  10360. Engine.prototype.addExternalData = function (key, data) {
  10361. return this._externalData.add(key, data);
  10362. };
  10363. /**
  10364. * Get an externaly attached data from its key
  10365. * @param key the unique key that identifies the data
  10366. * @return the associated data, if present (can be null), or undefined if not present
  10367. */
  10368. Engine.prototype.getExternalData = function (key) {
  10369. return this._externalData.get(key);
  10370. };
  10371. /**
  10372. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10373. * @param key the unique key that identifies the data
  10374. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10375. * @return the associated data, can be null if the factory returned null.
  10376. */
  10377. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10378. return this._externalData.getOrAddWithFactory(key, factory);
  10379. };
  10380. /**
  10381. * Remove an externaly attached data from the Engine instance
  10382. * @param key the unique key that identifies the data
  10383. * @return true if the data was successfully removed, false if it doesn't exist
  10384. */
  10385. Engine.prototype.removeExternalData = function (key) {
  10386. return this._externalData.remove(key);
  10387. };
  10388. Engine.prototype.releaseInternalTexture = function (texture) {
  10389. if (!texture) {
  10390. return;
  10391. }
  10392. texture.references--;
  10393. // Final reference ?
  10394. if (texture.references === 0) {
  10395. var texturesCache = this.getLoadedTexturesCache();
  10396. var index = texturesCache.indexOf(texture);
  10397. if (index > -1) {
  10398. texturesCache.splice(index, 1);
  10399. }
  10400. this._releaseTexture(texture);
  10401. }
  10402. };
  10403. Engine.prototype.unbindAllAttributes = function () {
  10404. if (this._mustWipeVertexAttributes) {
  10405. this._mustWipeVertexAttributes = false;
  10406. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10407. this._gl.disableVertexAttribArray(i);
  10408. this._vertexAttribArraysEnabled[i] = false;
  10409. this._currentBufferPointers[i] = null;
  10410. }
  10411. return;
  10412. }
  10413. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10414. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10415. continue;
  10416. }
  10417. this._gl.disableVertexAttribArray(i);
  10418. this._vertexAttribArraysEnabled[i] = false;
  10419. this._currentBufferPointers[i] = null;
  10420. }
  10421. };
  10422. // Dispose
  10423. Engine.prototype.dispose = function () {
  10424. this.hideLoadingUI();
  10425. this.stopRenderLoop();
  10426. // Release scenes
  10427. while (this.scenes.length) {
  10428. this.scenes[0].dispose();
  10429. }
  10430. // Release audio engine
  10431. Engine.audioEngine.dispose();
  10432. // Release effects
  10433. for (var name in this._compiledEffects) {
  10434. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10435. }
  10436. // Unbind
  10437. this.unbindAllAttributes();
  10438. this._gl = null;
  10439. //WebVR
  10440. this.disableVR();
  10441. // Events
  10442. window.removeEventListener("blur", this._onBlur);
  10443. window.removeEventListener("focus", this._onFocus);
  10444. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10445. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10446. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10447. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10448. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10449. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10450. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10451. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10452. // Remove from Instances
  10453. var index = Engine.Instances.indexOf(this);
  10454. if (index >= 0) {
  10455. Engine.Instances.splice(index, 1);
  10456. }
  10457. };
  10458. // Loading screen
  10459. Engine.prototype.displayLoadingUI = function () {
  10460. this._loadingScreen.displayLoadingUI();
  10461. };
  10462. Engine.prototype.hideLoadingUI = function () {
  10463. this._loadingScreen.hideLoadingUI();
  10464. };
  10465. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10466. get: function () {
  10467. return this._loadingScreen;
  10468. },
  10469. set: function (loadingScreen) {
  10470. this._loadingScreen = loadingScreen;
  10471. },
  10472. enumerable: true,
  10473. configurable: true
  10474. });
  10475. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10476. set: function (text) {
  10477. this._loadingScreen.loadingUIText = text;
  10478. },
  10479. enumerable: true,
  10480. configurable: true
  10481. });
  10482. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10483. set: function (color) {
  10484. this._loadingScreen.loadingUIBackgroundColor = color;
  10485. },
  10486. enumerable: true,
  10487. configurable: true
  10488. });
  10489. Engine.prototype.attachContextLostEvent = function (callback) {
  10490. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10491. };
  10492. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10493. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10494. };
  10495. Engine.prototype.getVertexShaderSource = function (program) {
  10496. var shaders = this._gl.getAttachedShaders(program);
  10497. return this._gl.getShaderSource(shaders[0]);
  10498. };
  10499. Engine.prototype.getFragmentShaderSource = function (program) {
  10500. var shaders = this._gl.getAttachedShaders(program);
  10501. return this._gl.getShaderSource(shaders[1]);
  10502. };
  10503. // FPS
  10504. Engine.prototype.getFps = function () {
  10505. return this.fps;
  10506. };
  10507. Engine.prototype.getDeltaTime = function () {
  10508. return this.deltaTime;
  10509. };
  10510. Engine.prototype._measureFps = function () {
  10511. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10512. var length = this.previousFramesDuration.length;
  10513. if (length >= 2) {
  10514. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10515. }
  10516. if (length >= this.fpsRange) {
  10517. if (length > this.fpsRange) {
  10518. this.previousFramesDuration.splice(0, 1);
  10519. length = this.previousFramesDuration.length;
  10520. }
  10521. var sum = 0;
  10522. for (var id = 0; id < length - 1; id++) {
  10523. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10524. }
  10525. this.fps = 1000.0 / (sum / (length - 1));
  10526. }
  10527. };
  10528. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10529. if (this._webGLVersion > 1) {
  10530. return this._caps.colorBufferFloat;
  10531. }
  10532. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10533. };
  10534. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10535. if (this._webGLVersion > 1) {
  10536. return this._caps.colorBufferFloat;
  10537. }
  10538. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10539. };
  10540. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10541. Engine.prototype._canRenderToFramebuffer = function (type) {
  10542. var gl = this._gl;
  10543. //clear existing errors
  10544. while (gl.getError() !== gl.NO_ERROR) { }
  10545. var successful = true;
  10546. var texture = gl.createTexture();
  10547. gl.bindTexture(gl.TEXTURE_2D, texture);
  10548. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10549. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10550. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10551. var fb = gl.createFramebuffer();
  10552. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10553. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10554. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10555. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10556. successful = successful && (gl.getError() === gl.NO_ERROR);
  10557. //try render by clearing frame buffer's color buffer
  10558. if (successful) {
  10559. gl.clear(gl.COLOR_BUFFER_BIT);
  10560. successful = successful && (gl.getError() === gl.NO_ERROR);
  10561. }
  10562. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10563. if (successful) {
  10564. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10565. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10566. var readFormat = gl.RGBA;
  10567. var readType = gl.UNSIGNED_BYTE;
  10568. var buffer = new Uint8Array(4);
  10569. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10570. successful = successful && (gl.getError() === gl.NO_ERROR);
  10571. }
  10572. //clean up
  10573. gl.deleteTexture(texture);
  10574. gl.deleteFramebuffer(fb);
  10575. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10576. //clear accumulated errors
  10577. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10578. return successful;
  10579. };
  10580. Engine.prototype._getWebGLTextureType = function (type) {
  10581. if (type === Engine.TEXTURETYPE_FLOAT) {
  10582. return this._gl.FLOAT;
  10583. }
  10584. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10585. // Add Half Float Constant.
  10586. return Engine.HALF_FLOAT_OES;
  10587. }
  10588. return this._gl.UNSIGNED_BYTE;
  10589. };
  10590. ;
  10591. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10592. if (this._webGLVersion === 1) {
  10593. return this._gl.RGBA;
  10594. }
  10595. if (type === Engine.TEXTURETYPE_FLOAT) {
  10596. return Engine.RGBA32F;
  10597. }
  10598. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10599. return Engine.RGBA16F;
  10600. }
  10601. return this._gl.RGBA;
  10602. };
  10603. ;
  10604. // Statics
  10605. Engine.isSupported = function () {
  10606. try {
  10607. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10608. if (navigator.isCocoonJS) {
  10609. return true;
  10610. }
  10611. var tempcanvas = document.createElement("canvas");
  10612. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10613. return gl != null && !!window.WebGLRenderingContext;
  10614. }
  10615. catch (e) {
  10616. return false;
  10617. }
  10618. };
  10619. return Engine;
  10620. }());
  10621. Engine.Instances = new Array();
  10622. // Const statics
  10623. Engine._ALPHA_DISABLE = 0;
  10624. Engine._ALPHA_ADD = 1;
  10625. Engine._ALPHA_COMBINE = 2;
  10626. Engine._ALPHA_SUBTRACT = 3;
  10627. Engine._ALPHA_MULTIPLY = 4;
  10628. Engine._ALPHA_MAXIMIZED = 5;
  10629. Engine._ALPHA_ONEONE = 6;
  10630. Engine._ALPHA_PREMULTIPLIED = 7;
  10631. Engine._DELAYLOADSTATE_NONE = 0;
  10632. Engine._DELAYLOADSTATE_LOADED = 1;
  10633. Engine._DELAYLOADSTATE_LOADING = 2;
  10634. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10635. Engine._TEXTUREFORMAT_ALPHA = 0;
  10636. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10637. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10638. Engine._TEXTUREFORMAT_RGB = 4;
  10639. Engine._TEXTUREFORMAT_RGBA = 5;
  10640. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10641. Engine._TEXTURETYPE_FLOAT = 1;
  10642. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10643. // Depht or Stencil test Constants.
  10644. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10645. 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.
  10646. 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.
  10647. 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.
  10648. 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.
  10649. 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.
  10650. 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.
  10651. 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.
  10652. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10653. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10654. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10655. // Stencil Actions Constants.
  10656. Engine._KEEP = 0x1E00;
  10657. Engine._REPLACE = 0x1E01;
  10658. Engine._INCR = 0x1E02;
  10659. Engine._DECR = 0x1E03;
  10660. Engine._INVERT = 0x150A;
  10661. Engine._INCR_WRAP = 0x8507;
  10662. Engine._DECR_WRAP = 0x8508;
  10663. // Updatable statics so stick with vars here
  10664. Engine.CollisionsEpsilon = 0.001;
  10665. Engine.CodeRepository = "src/";
  10666. Engine.ShadersRepository = "src/Shaders/";
  10667. BABYLON.Engine = Engine;
  10668. })(BABYLON || (BABYLON = {}));
  10669. //# sourceMappingURL=babylon.engine.js.map
  10670. /// <reference path="Tools\babylon.decorators.ts" />
  10671. var BABYLON;
  10672. (function (BABYLON) {
  10673. /**
  10674. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10675. */
  10676. var Node = (function () {
  10677. /**
  10678. * @constructor
  10679. * @param {string} name - the name and id to be given to this node
  10680. * @param {BABYLON.Scene} the scene this node will be added to
  10681. */
  10682. function Node(name, scene) {
  10683. this.state = "";
  10684. this.metadata = null;
  10685. this.doNotSerialize = false;
  10686. this.animations = new Array();
  10687. this._ranges = {};
  10688. this._childrenFlag = -1;
  10689. this._isEnabled = true;
  10690. this._isReady = true;
  10691. this._currentRenderId = -1;
  10692. this._parentRenderId = -1;
  10693. /**
  10694. * An event triggered when the mesh is disposed.
  10695. * @type {BABYLON.Observable}
  10696. */
  10697. this.onDisposeObservable = new BABYLON.Observable();
  10698. this.name = name;
  10699. this.id = name;
  10700. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10701. this._initCache();
  10702. }
  10703. Object.defineProperty(Node.prototype, "parent", {
  10704. get: function () {
  10705. return this._parentNode;
  10706. },
  10707. set: function (parent) {
  10708. if (this._parentNode === parent) {
  10709. return;
  10710. }
  10711. if (this._parentNode) {
  10712. var index = this._parentNode._children.indexOf(this);
  10713. if (index !== -1) {
  10714. this._parentNode._children.splice(index, 1);
  10715. }
  10716. }
  10717. this._parentNode = parent;
  10718. if (this._parentNode) {
  10719. if (!this._parentNode._children) {
  10720. this._parentNode._children = new Array();
  10721. }
  10722. this._parentNode._children.push(this);
  10723. }
  10724. },
  10725. enumerable: true,
  10726. configurable: true
  10727. });
  10728. Node.prototype.getClassName = function () {
  10729. return "Node";
  10730. };
  10731. Object.defineProperty(Node.prototype, "onDispose", {
  10732. set: function (callback) {
  10733. if (this._onDisposeObserver) {
  10734. this.onDisposeObservable.remove(this._onDisposeObserver);
  10735. }
  10736. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Node.prototype.getScene = function () {
  10742. return this._scene;
  10743. };
  10744. Node.prototype.getEngine = function () {
  10745. return this._scene.getEngine();
  10746. };
  10747. // override it in derived class
  10748. Node.prototype.getWorldMatrix = function () {
  10749. return BABYLON.Matrix.Identity();
  10750. };
  10751. // override it in derived class if you add new variables to the cache
  10752. // and call the parent class method
  10753. Node.prototype._initCache = function () {
  10754. this._cache = {};
  10755. this._cache.parent = undefined;
  10756. };
  10757. Node.prototype.updateCache = function (force) {
  10758. if (!force && this.isSynchronized())
  10759. return;
  10760. this._cache.parent = this.parent;
  10761. this._updateCache();
  10762. };
  10763. // override it in derived class if you add new variables to the cache
  10764. // and call the parent class method if !ignoreParentClass
  10765. Node.prototype._updateCache = function (ignoreParentClass) {
  10766. };
  10767. // override it in derived class if you add new variables to the cache
  10768. Node.prototype._isSynchronized = function () {
  10769. return true;
  10770. };
  10771. Node.prototype._markSyncedWithParent = function () {
  10772. this._parentRenderId = this.parent._currentRenderId;
  10773. };
  10774. Node.prototype.isSynchronizedWithParent = function () {
  10775. if (!this.parent) {
  10776. return true;
  10777. }
  10778. if (this._parentRenderId !== this.parent._currentRenderId) {
  10779. return false;
  10780. }
  10781. return this.parent.isSynchronized();
  10782. };
  10783. Node.prototype.isSynchronized = function (updateCache) {
  10784. var check = this.hasNewParent();
  10785. check = check || !this.isSynchronizedWithParent();
  10786. check = check || !this._isSynchronized();
  10787. if (updateCache)
  10788. this.updateCache(true);
  10789. return !check;
  10790. };
  10791. Node.prototype.hasNewParent = function (update) {
  10792. if (this._cache.parent === this.parent)
  10793. return false;
  10794. if (update)
  10795. this._cache.parent = this.parent;
  10796. return true;
  10797. };
  10798. /**
  10799. * Is this node ready to be used/rendered
  10800. * @return {boolean} is it ready
  10801. */
  10802. Node.prototype.isReady = function () {
  10803. return this._isReady;
  10804. };
  10805. /**
  10806. * Is this node enabled.
  10807. * If the node has a parent and is enabled, the parent will be inspected as well.
  10808. * @return {boolean} whether this node (and its parent) is enabled.
  10809. * @see setEnabled
  10810. */
  10811. Node.prototype.isEnabled = function () {
  10812. if (!this._isEnabled) {
  10813. return false;
  10814. }
  10815. if (this.parent) {
  10816. return this.parent.isEnabled();
  10817. }
  10818. return true;
  10819. };
  10820. /**
  10821. * Set the enabled state of this node.
  10822. * @param {boolean} value - the new enabled state
  10823. * @see isEnabled
  10824. */
  10825. Node.prototype.setEnabled = function (value) {
  10826. this._isEnabled = value;
  10827. };
  10828. /**
  10829. * Is this node a descendant of the given node.
  10830. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10831. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10832. * @see parent
  10833. */
  10834. Node.prototype.isDescendantOf = function (ancestor) {
  10835. if (this.parent) {
  10836. if (this.parent === ancestor) {
  10837. return true;
  10838. }
  10839. return this.parent.isDescendantOf(ancestor);
  10840. }
  10841. return false;
  10842. };
  10843. /**
  10844. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10845. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10846. * @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.
  10847. * @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.
  10848. */
  10849. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10850. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10851. if (!this._children) {
  10852. return;
  10853. }
  10854. for (var index = 0; index < this._children.length; index++) {
  10855. var item = this._children[index];
  10856. if (!predicate || predicate(item)) {
  10857. results.push(item);
  10858. }
  10859. if (!directDescendantsOnly) {
  10860. item._getDescendants(results, false, predicate);
  10861. }
  10862. }
  10863. };
  10864. /**
  10865. * Will return all nodes that have this node as ascendant.
  10866. * @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.
  10867. * @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.
  10868. * @return {BABYLON.Node[]} all children nodes of all types.
  10869. */
  10870. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10871. var results = [];
  10872. this._getDescendants(results, directDescendantsOnly, predicate);
  10873. return results;
  10874. };
  10875. /**
  10876. * Get all child-meshes of this node.
  10877. */
  10878. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10879. var results = [];
  10880. this._getDescendants(results, directDecendantsOnly, function (node) {
  10881. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10882. });
  10883. return results;
  10884. };
  10885. Node.prototype._setReady = function (state) {
  10886. if (state === this._isReady) {
  10887. return;
  10888. }
  10889. if (!state) {
  10890. this._isReady = false;
  10891. return;
  10892. }
  10893. this._isReady = true;
  10894. if (this.onReady) {
  10895. this.onReady(this);
  10896. }
  10897. };
  10898. Node.prototype.getAnimationByName = function (name) {
  10899. for (var i = 0; i < this.animations.length; i++) {
  10900. var animation = this.animations[i];
  10901. if (animation.name === name) {
  10902. return animation;
  10903. }
  10904. }
  10905. return null;
  10906. };
  10907. Node.prototype.createAnimationRange = function (name, from, to) {
  10908. // check name not already in use
  10909. if (!this._ranges[name]) {
  10910. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10911. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10912. if (this.animations[i]) {
  10913. this.animations[i].createRange(name, from, to);
  10914. }
  10915. }
  10916. }
  10917. };
  10918. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10919. if (deleteFrames === void 0) { deleteFrames = true; }
  10920. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10921. if (this.animations[i]) {
  10922. this.animations[i].deleteRange(name, deleteFrames);
  10923. }
  10924. }
  10925. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10926. };
  10927. Node.prototype.getAnimationRange = function (name) {
  10928. return this._ranges[name];
  10929. };
  10930. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10931. var range = this.getAnimationRange(name);
  10932. if (!range) {
  10933. return null;
  10934. }
  10935. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10936. };
  10937. Node.prototype.serializeAnimationRanges = function () {
  10938. var serializationRanges = [];
  10939. for (var name in this._ranges) {
  10940. var range = {};
  10941. range.name = name;
  10942. range.from = this._ranges[name].from;
  10943. range.to = this._ranges[name].to;
  10944. serializationRanges.push(range);
  10945. }
  10946. return serializationRanges;
  10947. };
  10948. Node.prototype.dispose = function () {
  10949. this.parent = null;
  10950. // Callback
  10951. this.onDisposeObservable.notifyObservers(this);
  10952. this.onDisposeObservable.clear();
  10953. };
  10954. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10955. if (parsedNode.ranges) {
  10956. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10957. var data = parsedNode.ranges[index];
  10958. node.createAnimationRange(data.name, data.from, data.to);
  10959. }
  10960. }
  10961. };
  10962. return Node;
  10963. }());
  10964. __decorate([
  10965. BABYLON.serialize()
  10966. ], Node.prototype, "name", void 0);
  10967. __decorate([
  10968. BABYLON.serialize()
  10969. ], Node.prototype, "id", void 0);
  10970. __decorate([
  10971. BABYLON.serialize()
  10972. ], Node.prototype, "uniqueId", void 0);
  10973. __decorate([
  10974. BABYLON.serialize()
  10975. ], Node.prototype, "state", void 0);
  10976. __decorate([
  10977. BABYLON.serialize()
  10978. ], Node.prototype, "metadata", void 0);
  10979. BABYLON.Node = Node;
  10980. })(BABYLON || (BABYLON = {}));
  10981. //# sourceMappingURL=babylon.node.js.map
  10982. var BABYLON;
  10983. (function (BABYLON) {
  10984. var FilesInput = (function () {
  10985. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  10986. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  10987. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  10988. this._engine = p_engine;
  10989. this._canvas = p_canvas;
  10990. this._currentScene = p_scene;
  10991. this._sceneLoadedCallback = p_sceneLoadedCallback;
  10992. this._progressCallback = p_progressCallback;
  10993. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  10994. this._textureLoadingCallback = p_textureLoadingCallback;
  10995. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  10996. }
  10997. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  10998. var _this = this;
  10999. if (p_elementToMonitor) {
  11000. this._elementToMonitor = p_elementToMonitor;
  11001. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11002. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11003. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11004. }
  11005. };
  11006. FilesInput.prototype.renderFunction = function () {
  11007. if (this._additionnalRenderLoopLogicCallback) {
  11008. this._additionnalRenderLoopLogicCallback();
  11009. }
  11010. if (this._currentScene) {
  11011. if (this._textureLoadingCallback) {
  11012. var remaining = this._currentScene.getWaitingItemsCount();
  11013. if (remaining > 0) {
  11014. this._textureLoadingCallback(remaining);
  11015. }
  11016. }
  11017. this._currentScene.render();
  11018. }
  11019. };
  11020. FilesInput.prototype.drag = function (e) {
  11021. e.stopPropagation();
  11022. e.preventDefault();
  11023. };
  11024. FilesInput.prototype.drop = function (eventDrop) {
  11025. eventDrop.stopPropagation();
  11026. eventDrop.preventDefault();
  11027. this.loadFiles(eventDrop);
  11028. };
  11029. FilesInput.prototype.loadFiles = function (event) {
  11030. if (this._startingProcessingFilesCallback)
  11031. this._startingProcessingFilesCallback();
  11032. // Handling data transfer via drag'n'drop
  11033. if (event && event.dataTransfer && event.dataTransfer.files) {
  11034. this._filesToLoad = event.dataTransfer.files;
  11035. }
  11036. // Handling files from input files
  11037. if (event && event.target && event.target.files) {
  11038. this._filesToLoad = event.target.files;
  11039. }
  11040. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11041. for (var i = 0; i < this._filesToLoad.length; i++) {
  11042. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11043. var extension = name_1.split('.').pop();
  11044. var type = this._filesToLoad[i].type;
  11045. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11046. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11047. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11048. }
  11049. else {
  11050. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11051. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11052. this._sceneFileToLoad = this._filesToLoad[i];
  11053. }
  11054. else {
  11055. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11056. }
  11057. }
  11058. }
  11059. this.reload();
  11060. }
  11061. };
  11062. FilesInput.prototype.reload = function () {
  11063. var _this = this;
  11064. var that = this;
  11065. // If a ".babylon" file has been provided
  11066. if (this._sceneFileToLoad) {
  11067. if (this._currentScene) {
  11068. if (BABYLON.Tools.errorsCount > 0) {
  11069. BABYLON.Tools.ClearLogCache();
  11070. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11071. }
  11072. this._engine.stopRenderLoop();
  11073. this._currentScene.dispose();
  11074. }
  11075. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11076. that._currentScene = newScene;
  11077. // Wait for textures and shaders to be ready
  11078. that._currentScene.executeWhenReady(function () {
  11079. // Attach camera to canvas inputs
  11080. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11081. that._currentScene.createDefaultCameraOrLight();
  11082. }
  11083. that._currentScene.activeCamera.attachControl(that._canvas);
  11084. if (that._sceneLoadedCallback) {
  11085. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11086. }
  11087. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11088. });
  11089. }, function (progress) {
  11090. if (_this._progressCallback) {
  11091. _this._progressCallback(progress);
  11092. }
  11093. });
  11094. }
  11095. else {
  11096. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11097. }
  11098. };
  11099. return FilesInput;
  11100. }());
  11101. FilesInput.FilesTextures = new Array();
  11102. FilesInput.FilesToLoad = new Array();
  11103. BABYLON.FilesInput = FilesInput;
  11104. })(BABYLON || (BABYLON = {}));
  11105. //# sourceMappingURL=babylon.filesInput.js.map
  11106. var BABYLON;
  11107. (function (BABYLON) {
  11108. var IntersectionInfo = (function () {
  11109. function IntersectionInfo(bu, bv, distance) {
  11110. this.bu = bu;
  11111. this.bv = bv;
  11112. this.distance = distance;
  11113. this.faceId = 0;
  11114. this.subMeshId = 0;
  11115. }
  11116. return IntersectionInfo;
  11117. }());
  11118. BABYLON.IntersectionInfo = IntersectionInfo;
  11119. var PickingInfo = (function () {
  11120. function PickingInfo() {
  11121. this.hit = false;
  11122. this.distance = 0;
  11123. this.pickedPoint = null;
  11124. this.pickedMesh = null;
  11125. this.bu = 0;
  11126. this.bv = 0;
  11127. this.faceId = -1;
  11128. this.subMeshId = 0;
  11129. this.pickedSprite = null;
  11130. }
  11131. // Methods
  11132. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11133. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11134. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11135. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11136. return null;
  11137. }
  11138. var indices = this.pickedMesh.getIndices();
  11139. var result;
  11140. if (useVerticesNormals) {
  11141. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11142. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11143. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11144. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11145. normal0 = normal0.scale(this.bu);
  11146. normal1 = normal1.scale(this.bv);
  11147. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11148. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11149. }
  11150. else {
  11151. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11152. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11153. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11154. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11155. var p1p2 = vertex1.subtract(vertex2);
  11156. var p3p2 = vertex3.subtract(vertex2);
  11157. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11158. }
  11159. if (useWorldCoordinates) {
  11160. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11161. }
  11162. return BABYLON.Vector3.Normalize(result);
  11163. };
  11164. PickingInfo.prototype.getTextureCoordinates = function () {
  11165. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11166. return null;
  11167. }
  11168. var indices = this.pickedMesh.getIndices();
  11169. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11170. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11171. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11172. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11173. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11174. uv1 = uv1.scale(this.bu);
  11175. uv2 = uv2.scale(this.bv);
  11176. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11177. };
  11178. return PickingInfo;
  11179. }());
  11180. BABYLON.PickingInfo = PickingInfo;
  11181. })(BABYLON || (BABYLON = {}));
  11182. //# sourceMappingURL=babylon.pickingInfo.js.map
  11183. var BABYLON;
  11184. (function (BABYLON) {
  11185. var BoundingSphere = (function () {
  11186. function BoundingSphere(minimum, maximum) {
  11187. this.minimum = minimum;
  11188. this.maximum = maximum;
  11189. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11190. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11191. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11192. this.radius = distance * 0.5;
  11193. this.centerWorld = BABYLON.Vector3.Zero();
  11194. this._update(BABYLON.Matrix.Identity());
  11195. }
  11196. // Methods
  11197. BoundingSphere.prototype._update = function (world) {
  11198. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11199. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11200. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11201. };
  11202. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11203. for (var i = 0; i < 6; i++) {
  11204. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11205. return false;
  11206. }
  11207. return true;
  11208. };
  11209. BoundingSphere.prototype.intersectsPoint = function (point) {
  11210. var x = this.centerWorld.x - point.x;
  11211. var y = this.centerWorld.y - point.y;
  11212. var z = this.centerWorld.z - point.z;
  11213. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11214. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11215. return false;
  11216. return true;
  11217. };
  11218. // Statics
  11219. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11220. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11221. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11222. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11223. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11224. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11225. return false;
  11226. return true;
  11227. };
  11228. return BoundingSphere;
  11229. }());
  11230. BABYLON.BoundingSphere = BoundingSphere;
  11231. })(BABYLON || (BABYLON = {}));
  11232. //# sourceMappingURL=babylon.boundingSphere.js.map
  11233. var BABYLON;
  11234. (function (BABYLON) {
  11235. var BoundingBox = (function () {
  11236. function BoundingBox(minimum, maximum) {
  11237. this.minimum = minimum;
  11238. this.maximum = maximum;
  11239. this.vectors = new Array();
  11240. this.vectorsWorld = new Array();
  11241. // Bounding vectors
  11242. this.vectors.push(this.minimum.clone());
  11243. this.vectors.push(this.maximum.clone());
  11244. this.vectors.push(this.minimum.clone());
  11245. this.vectors[2].x = this.maximum.x;
  11246. this.vectors.push(this.minimum.clone());
  11247. this.vectors[3].y = this.maximum.y;
  11248. this.vectors.push(this.minimum.clone());
  11249. this.vectors[4].z = this.maximum.z;
  11250. this.vectors.push(this.maximum.clone());
  11251. this.vectors[5].z = this.minimum.z;
  11252. this.vectors.push(this.maximum.clone());
  11253. this.vectors[6].x = this.minimum.x;
  11254. this.vectors.push(this.maximum.clone());
  11255. this.vectors[7].y = this.minimum.y;
  11256. // OBB
  11257. this.center = this.maximum.add(this.minimum).scale(0.5);
  11258. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11259. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11260. // World
  11261. for (var index = 0; index < this.vectors.length; index++) {
  11262. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11263. }
  11264. this.minimumWorld = BABYLON.Vector3.Zero();
  11265. this.maximumWorld = BABYLON.Vector3.Zero();
  11266. this._update(BABYLON.Matrix.Identity());
  11267. }
  11268. // Methods
  11269. BoundingBox.prototype.getWorldMatrix = function () {
  11270. return this._worldMatrix;
  11271. };
  11272. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11273. this._worldMatrix.copyFrom(matrix);
  11274. return this;
  11275. };
  11276. BoundingBox.prototype._update = function (world) {
  11277. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11278. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11279. for (var index = 0; index < this.vectors.length; index++) {
  11280. var v = this.vectorsWorld[index];
  11281. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11282. if (v.x < this.minimumWorld.x)
  11283. this.minimumWorld.x = v.x;
  11284. if (v.y < this.minimumWorld.y)
  11285. this.minimumWorld.y = v.y;
  11286. if (v.z < this.minimumWorld.z)
  11287. this.minimumWorld.z = v.z;
  11288. if (v.x > this.maximumWorld.x)
  11289. this.maximumWorld.x = v.x;
  11290. if (v.y > this.maximumWorld.y)
  11291. this.maximumWorld.y = v.y;
  11292. if (v.z > this.maximumWorld.z)
  11293. this.maximumWorld.z = v.z;
  11294. }
  11295. // OBB
  11296. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  11297. this.center.scaleInPlace(0.5);
  11298. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11299. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11300. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11301. this._worldMatrix = world;
  11302. };
  11303. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11304. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11305. };
  11306. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11307. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11308. };
  11309. BoundingBox.prototype.intersectsPoint = function (point) {
  11310. var delta = -BABYLON.Epsilon;
  11311. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11312. return false;
  11313. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11314. return false;
  11315. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11316. return false;
  11317. return true;
  11318. };
  11319. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11320. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11321. };
  11322. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11323. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11324. return false;
  11325. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11326. return false;
  11327. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11328. return false;
  11329. return true;
  11330. };
  11331. // Statics
  11332. BoundingBox.Intersects = function (box0, box1) {
  11333. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11334. return false;
  11335. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11336. return false;
  11337. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11338. return false;
  11339. return true;
  11340. };
  11341. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11342. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11343. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11344. return (num <= (sphereRadius * sphereRadius));
  11345. };
  11346. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11347. for (var p = 0; p < 6; p++) {
  11348. for (var i = 0; i < 8; i++) {
  11349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11350. return false;
  11351. }
  11352. }
  11353. }
  11354. return true;
  11355. };
  11356. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11357. for (var p = 0; p < 6; p++) {
  11358. var inCount = 8;
  11359. for (var i = 0; i < 8; i++) {
  11360. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11361. --inCount;
  11362. }
  11363. else {
  11364. break;
  11365. }
  11366. }
  11367. if (inCount === 0)
  11368. return false;
  11369. }
  11370. return true;
  11371. };
  11372. return BoundingBox;
  11373. }());
  11374. BABYLON.BoundingBox = BoundingBox;
  11375. })(BABYLON || (BABYLON = {}));
  11376. //# sourceMappingURL=babylon.boundingBox.js.map
  11377. var BABYLON;
  11378. (function (BABYLON) {
  11379. var computeBoxExtents = function (axis, box) {
  11380. var p = BABYLON.Vector3.Dot(box.center, axis);
  11381. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11382. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11383. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11384. var r = r0 + r1 + r2;
  11385. return {
  11386. min: p - r,
  11387. max: p + r
  11388. };
  11389. };
  11390. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11391. var axisOverlap = function (axis, box0, box1) {
  11392. var result0 = computeBoxExtents(axis, box0);
  11393. var result1 = computeBoxExtents(axis, box1);
  11394. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11395. };
  11396. var BoundingInfo = (function () {
  11397. function BoundingInfo(minimum, maximum) {
  11398. this.minimum = minimum;
  11399. this.maximum = maximum;
  11400. this._isLocked = false;
  11401. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11402. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11403. }
  11404. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11405. get: function () {
  11406. return this._isLocked;
  11407. },
  11408. set: function (value) {
  11409. this._isLocked = value;
  11410. },
  11411. enumerable: true,
  11412. configurable: true
  11413. });
  11414. // Methods
  11415. BoundingInfo.prototype.update = function (world) {
  11416. if (this._isLocked) {
  11417. return;
  11418. }
  11419. this.boundingBox._update(world);
  11420. this.boundingSphere._update(world);
  11421. };
  11422. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11423. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11424. return false;
  11425. return this.boundingBox.isInFrustum(frustumPlanes);
  11426. };
  11427. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11428. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11429. };
  11430. BoundingInfo.prototype._checkCollision = function (collider) {
  11431. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11432. };
  11433. BoundingInfo.prototype.intersectsPoint = function (point) {
  11434. if (!this.boundingSphere.centerWorld) {
  11435. return false;
  11436. }
  11437. if (!this.boundingSphere.intersectsPoint(point)) {
  11438. return false;
  11439. }
  11440. if (!this.boundingBox.intersectsPoint(point)) {
  11441. return false;
  11442. }
  11443. return true;
  11444. };
  11445. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11446. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11447. return false;
  11448. }
  11449. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11450. return false;
  11451. }
  11452. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11453. return false;
  11454. }
  11455. if (!precise) {
  11456. return true;
  11457. }
  11458. var box0 = this.boundingBox;
  11459. var box1 = boundingInfo.boundingBox;
  11460. if (!axisOverlap(box0.directions[0], box0, box1))
  11461. return false;
  11462. if (!axisOverlap(box0.directions[1], box0, box1))
  11463. return false;
  11464. if (!axisOverlap(box0.directions[2], box0, box1))
  11465. return false;
  11466. if (!axisOverlap(box1.directions[0], box0, box1))
  11467. return false;
  11468. if (!axisOverlap(box1.directions[1], box0, box1))
  11469. return false;
  11470. if (!axisOverlap(box1.directions[2], box0, box1))
  11471. return false;
  11472. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11473. return false;
  11474. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11475. return false;
  11476. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11477. return false;
  11478. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11479. return false;
  11480. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11481. return false;
  11482. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11483. return false;
  11484. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11485. return false;
  11486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11487. return false;
  11488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11489. return false;
  11490. return true;
  11491. };
  11492. return BoundingInfo;
  11493. }());
  11494. BABYLON.BoundingInfo = BoundingInfo;
  11495. })(BABYLON || (BABYLON = {}));
  11496. //# sourceMappingURL=babylon.boundingInfo.js.map
  11497. var BABYLON;
  11498. (function (BABYLON) {
  11499. var Ray = (function () {
  11500. function Ray(origin, direction, length) {
  11501. if (length === void 0) { length = Number.MAX_VALUE; }
  11502. this.origin = origin;
  11503. this.direction = direction;
  11504. this.length = length;
  11505. }
  11506. // Methods
  11507. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11508. var d = 0.0;
  11509. var maxValue = Number.MAX_VALUE;
  11510. var inv;
  11511. var min;
  11512. var max;
  11513. var temp;
  11514. if (Math.abs(this.direction.x) < 0.0000001) {
  11515. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11516. return false;
  11517. }
  11518. }
  11519. else {
  11520. inv = 1.0 / this.direction.x;
  11521. min = (minimum.x - this.origin.x) * inv;
  11522. max = (maximum.x - this.origin.x) * inv;
  11523. if (max === -Infinity) {
  11524. max = Infinity;
  11525. }
  11526. if (min > max) {
  11527. temp = min;
  11528. min = max;
  11529. max = temp;
  11530. }
  11531. d = Math.max(min, d);
  11532. maxValue = Math.min(max, maxValue);
  11533. if (d > maxValue) {
  11534. return false;
  11535. }
  11536. }
  11537. if (Math.abs(this.direction.y) < 0.0000001) {
  11538. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11539. return false;
  11540. }
  11541. }
  11542. else {
  11543. inv = 1.0 / this.direction.y;
  11544. min = (minimum.y - this.origin.y) * inv;
  11545. max = (maximum.y - this.origin.y) * inv;
  11546. if (max === -Infinity) {
  11547. max = Infinity;
  11548. }
  11549. if (min > max) {
  11550. temp = min;
  11551. min = max;
  11552. max = temp;
  11553. }
  11554. d = Math.max(min, d);
  11555. maxValue = Math.min(max, maxValue);
  11556. if (d > maxValue) {
  11557. return false;
  11558. }
  11559. }
  11560. if (Math.abs(this.direction.z) < 0.0000001) {
  11561. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11562. return false;
  11563. }
  11564. }
  11565. else {
  11566. inv = 1.0 / this.direction.z;
  11567. min = (minimum.z - this.origin.z) * inv;
  11568. max = (maximum.z - this.origin.z) * inv;
  11569. if (max === -Infinity) {
  11570. max = Infinity;
  11571. }
  11572. if (min > max) {
  11573. temp = min;
  11574. min = max;
  11575. max = temp;
  11576. }
  11577. d = Math.max(min, d);
  11578. maxValue = Math.min(max, maxValue);
  11579. if (d > maxValue) {
  11580. return false;
  11581. }
  11582. }
  11583. return true;
  11584. };
  11585. Ray.prototype.intersectsBox = function (box) {
  11586. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11587. };
  11588. Ray.prototype.intersectsSphere = function (sphere) {
  11589. var x = sphere.center.x - this.origin.x;
  11590. var y = sphere.center.y - this.origin.y;
  11591. var z = sphere.center.z - this.origin.z;
  11592. var pyth = (x * x) + (y * y) + (z * z);
  11593. var rr = sphere.radius * sphere.radius;
  11594. if (pyth <= rr) {
  11595. return true;
  11596. }
  11597. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11598. if (dot < 0.0) {
  11599. return false;
  11600. }
  11601. var temp = pyth - (dot * dot);
  11602. return temp <= rr;
  11603. };
  11604. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11605. if (!this._edge1) {
  11606. this._edge1 = BABYLON.Vector3.Zero();
  11607. this._edge2 = BABYLON.Vector3.Zero();
  11608. this._pvec = BABYLON.Vector3.Zero();
  11609. this._tvec = BABYLON.Vector3.Zero();
  11610. this._qvec = BABYLON.Vector3.Zero();
  11611. }
  11612. vertex1.subtractToRef(vertex0, this._edge1);
  11613. vertex2.subtractToRef(vertex0, this._edge2);
  11614. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11615. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11616. if (det === 0) {
  11617. return null;
  11618. }
  11619. var invdet = 1 / det;
  11620. this.origin.subtractToRef(vertex0, this._tvec);
  11621. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11622. if (bu < 0 || bu > 1.0) {
  11623. return null;
  11624. }
  11625. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11626. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11627. if (bv < 0 || bu + bv > 1.0) {
  11628. return null;
  11629. }
  11630. //check if the distance is longer than the predefined length.
  11631. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11632. if (distance > this.length) {
  11633. return null;
  11634. }
  11635. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11636. };
  11637. Ray.prototype.intersectsPlane = function (plane) {
  11638. var distance;
  11639. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11640. if (Math.abs(result1) < 9.99999997475243E-07) {
  11641. return null;
  11642. }
  11643. else {
  11644. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11645. distance = (-plane.d - result2) / result1;
  11646. if (distance < 0.0) {
  11647. if (distance < -9.99999997475243E-07) {
  11648. return null;
  11649. }
  11650. else {
  11651. return 0;
  11652. }
  11653. }
  11654. return distance;
  11655. }
  11656. };
  11657. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11658. var tm = BABYLON.Tmp.Matrix[0];
  11659. mesh.getWorldMatrix().invertToRef(tm);
  11660. if (this._tmpRay) {
  11661. Ray.TransformToRef(this, tm, this._tmpRay);
  11662. }
  11663. else {
  11664. this._tmpRay = Ray.Transform(this, tm);
  11665. }
  11666. return mesh.intersects(this._tmpRay, fastCheck);
  11667. };
  11668. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11669. if (results) {
  11670. results.length = 0;
  11671. }
  11672. else {
  11673. results = [];
  11674. }
  11675. for (var i = 0; i < meshes.length; i++) {
  11676. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11677. if (pickInfo.hit) {
  11678. results.push(pickInfo);
  11679. }
  11680. }
  11681. results.sort(this._comparePickingInfo);
  11682. return results;
  11683. };
  11684. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11685. if (pickingInfoA.distance < pickingInfoB.distance) {
  11686. return -1;
  11687. }
  11688. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11689. return 1;
  11690. }
  11691. else {
  11692. return 0;
  11693. }
  11694. };
  11695. /**
  11696. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11697. * @param sega the first point of the segment to test the intersection against
  11698. * @param segb the second point of the segment to test the intersection against
  11699. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11700. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11701. */
  11702. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11703. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11704. var u = segb.subtract(sega);
  11705. var v = rsegb.subtract(this.origin);
  11706. var w = sega.subtract(this.origin);
  11707. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11708. var b = BABYLON.Vector3.Dot(u, v);
  11709. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11710. var d = BABYLON.Vector3.Dot(u, w);
  11711. var e = BABYLON.Vector3.Dot(v, w);
  11712. var D = a * c - b * b; // always >= 0
  11713. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11714. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11715. // compute the line parameters of the two closest points
  11716. if (D < Ray.smallnum) {
  11717. sN = 0.0; // force using point P0 on segment S1
  11718. sD = 1.0; // to prevent possible division by 0.0 later
  11719. tN = e;
  11720. tD = c;
  11721. }
  11722. else {
  11723. sN = (b * e - c * d);
  11724. tN = (a * e - b * d);
  11725. if (sN < 0.0) {
  11726. sN = 0.0;
  11727. tN = e;
  11728. tD = c;
  11729. }
  11730. else if (sN > sD) {
  11731. sN = sD;
  11732. tN = e + b;
  11733. tD = c;
  11734. }
  11735. }
  11736. if (tN < 0.0) {
  11737. tN = 0.0;
  11738. // recompute sc for this edge
  11739. if (-d < 0.0) {
  11740. sN = 0.0;
  11741. }
  11742. else if (-d > a)
  11743. sN = sD;
  11744. else {
  11745. sN = -d;
  11746. sD = a;
  11747. }
  11748. }
  11749. else if (tN > tD) {
  11750. tN = tD;
  11751. // recompute sc for this edge
  11752. if ((-d + b) < 0.0) {
  11753. sN = 0;
  11754. }
  11755. else if ((-d + b) > a) {
  11756. sN = sD;
  11757. }
  11758. else {
  11759. sN = (-d + b);
  11760. sD = a;
  11761. }
  11762. }
  11763. // finally do the division to get sc and tc
  11764. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11765. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11766. // get the difference of the two closest points
  11767. var qtc = v.multiplyByFloats(tc, tc, tc);
  11768. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11769. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11770. if (isIntersected) {
  11771. return qtc.length();
  11772. }
  11773. return -1;
  11774. };
  11775. // Statics
  11776. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11777. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11778. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11779. var direction = end.subtract(start);
  11780. direction.normalize();
  11781. return new Ray(start, direction);
  11782. };
  11783. /**
  11784. * 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
  11785. * transformed to the given world matrix.
  11786. * @param origin The origin point
  11787. * @param end The end point
  11788. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11789. */
  11790. Ray.CreateNewFromTo = function (origin, end, world) {
  11791. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11792. var direction = end.subtract(origin);
  11793. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11794. direction.normalize();
  11795. return Ray.Transform(new Ray(origin, direction, length), world);
  11796. };
  11797. Ray.Transform = function (ray, matrix) {
  11798. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11799. Ray.TransformToRef(ray, matrix, result);
  11800. return result;
  11801. };
  11802. Ray.TransformToRef = function (ray, matrix, result) {
  11803. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11804. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11805. result.length = ray.length;
  11806. var dir = result.direction;
  11807. var len = dir.length();
  11808. if (!(len === 0 || len === 1)) {
  11809. var num = 1.0 / len;
  11810. dir.x *= num;
  11811. dir.y *= num;
  11812. dir.z *= num;
  11813. result.length *= len;
  11814. }
  11815. };
  11816. return Ray;
  11817. }());
  11818. Ray.smallnum = 0.00000001;
  11819. Ray.rayl = 10e8;
  11820. BABYLON.Ray = Ray;
  11821. })(BABYLON || (BABYLON = {}));
  11822. //# sourceMappingURL=babylon.ray.js.map
  11823. var BABYLON;
  11824. (function (BABYLON) {
  11825. var RayHelper = (function () {
  11826. function RayHelper(ray) {
  11827. this.ray = ray;
  11828. }
  11829. RayHelper.prototype.show = function (scene, color) {
  11830. if (!this._renderFunction) {
  11831. var ray = this.ray;
  11832. this._renderFunction = this._render.bind(this);
  11833. this._scene = scene;
  11834. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11835. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11836. this._scene.registerBeforeRender(this._renderFunction);
  11837. }
  11838. if (color) {
  11839. this._renderLine.color.copyFrom(color);
  11840. }
  11841. };
  11842. RayHelper.prototype.hide = function () {
  11843. if (this._renderFunction) {
  11844. this._scene.unregisterBeforeRender(this._renderFunction);
  11845. this._scene = null;
  11846. this._renderFunction = null;
  11847. this._renderLine.dispose();
  11848. this._renderLine = null;
  11849. this._renderPoints = null;
  11850. }
  11851. };
  11852. RayHelper.prototype._render = function () {
  11853. var ray = this.ray;
  11854. var point = this._renderPoints[1];
  11855. var len = Math.min(ray.length, 1000000);
  11856. point.copyFrom(ray.direction);
  11857. point.scaleInPlace(len);
  11858. point.addInPlace(ray.origin);
  11859. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11860. };
  11861. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11862. this._attachedToMesh = mesh;
  11863. var ray = this.ray;
  11864. if (!ray.direction) {
  11865. ray.direction = BABYLON.Vector3.Zero();
  11866. }
  11867. if (!ray.origin) {
  11868. ray.origin = BABYLON.Vector3.Zero();
  11869. }
  11870. if (length) {
  11871. ray.length = length;
  11872. }
  11873. if (!meshSpaceOrigin) {
  11874. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11875. }
  11876. if (!meshSpaceDirection) {
  11877. // -1 so that this will work with Mesh.lookAt
  11878. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11879. }
  11880. if (!this._meshSpaceDirection) {
  11881. this._meshSpaceDirection = meshSpaceDirection.clone();
  11882. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11883. }
  11884. else {
  11885. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  11886. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  11887. }
  11888. if (!this._updateToMeshFunction) {
  11889. this._updateToMeshFunction = this._updateToMesh.bind(this);
  11890. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  11891. }
  11892. this._updateToMesh();
  11893. };
  11894. RayHelper.prototype.detachFromMesh = function () {
  11895. if (this._attachedToMesh) {
  11896. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  11897. this._attachedToMesh = null;
  11898. this._updateToMeshFunction = null;
  11899. }
  11900. };
  11901. RayHelper.prototype._updateToMesh = function () {
  11902. var ray = this.ray;
  11903. if (this._attachedToMesh._isDisposed) {
  11904. this.detachFromMesh();
  11905. return;
  11906. }
  11907. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  11908. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  11909. };
  11910. RayHelper.prototype.dispose = function () {
  11911. this.hide();
  11912. this.detachFromMesh();
  11913. this.ray = null;
  11914. };
  11915. return RayHelper;
  11916. }());
  11917. BABYLON.RayHelper = RayHelper;
  11918. })(BABYLON || (BABYLON = {}));
  11919. //# sourceMappingURL=babylon.rayHelper.js.map
  11920. var BABYLON;
  11921. (function (BABYLON) {
  11922. var AbstractMesh = (function (_super) {
  11923. __extends(AbstractMesh, _super);
  11924. // Constructor
  11925. function AbstractMesh(name, scene) {
  11926. var _this = _super.call(this, name, scene) || this;
  11927. _this._facetNb = 0; // facet number
  11928. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11929. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11930. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11931. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11932. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11933. _this._subDiv = {
  11934. max: 1,
  11935. X: 1,
  11936. Y: 1,
  11937. Z: 1
  11938. };
  11939. // Events
  11940. /**
  11941. * An event triggered when this mesh collides with another one
  11942. * @type {BABYLON.Observable}
  11943. */
  11944. _this.onCollideObservable = new BABYLON.Observable();
  11945. /**
  11946. * An event triggered when the collision's position changes
  11947. * @type {BABYLON.Observable}
  11948. */
  11949. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11950. /**
  11951. * An event triggered after the world matrix is updated
  11952. * @type {BABYLON.Observable}
  11953. */
  11954. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11955. // Properties
  11956. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11957. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11958. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11959. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11960. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11961. _this.visibility = 1.0;
  11962. _this.alphaIndex = Number.MAX_VALUE;
  11963. _this.infiniteDistance = false;
  11964. _this.isVisible = true;
  11965. _this.isPickable = true;
  11966. _this.showBoundingBox = false;
  11967. _this.showSubMeshesBoundingBox = false;
  11968. _this.isBlocker = false;
  11969. _this.renderingGroupId = 0;
  11970. _this.receiveShadows = false;
  11971. _this.renderOutline = false;
  11972. _this.outlineColor = BABYLON.Color3.Red();
  11973. _this.outlineWidth = 0.02;
  11974. _this.renderOverlay = false;
  11975. _this.overlayColor = BABYLON.Color3.Red();
  11976. _this.overlayAlpha = 0.5;
  11977. _this.hasVertexAlpha = false;
  11978. _this.useVertexColors = true;
  11979. _this.applyFog = true;
  11980. _this.computeBonesUsingShaders = true;
  11981. _this.scalingDeterminant = 1;
  11982. _this.numBoneInfluencers = 4;
  11983. _this.useOctreeForRenderingSelection = true;
  11984. _this.useOctreeForPicking = true;
  11985. _this.useOctreeForCollisions = true;
  11986. _this.layerMask = 0x0FFFFFFF;
  11987. /**
  11988. * True if the mesh must be rendered in any case.
  11989. */
  11990. _this.alwaysSelectAsActiveMesh = false;
  11991. // Collisions
  11992. _this._checkCollisions = false;
  11993. _this._collisionMask = -1;
  11994. _this._collisionGroup = -1;
  11995. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11996. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11997. _this._collider = new BABYLON.Collider();
  11998. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11999. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12000. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12001. // Edges
  12002. _this.edgesWidth = 1;
  12003. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12004. // Cache
  12005. _this._localWorld = BABYLON.Matrix.Zero();
  12006. _this._worldMatrix = BABYLON.Matrix.Zero();
  12007. _this._absolutePosition = BABYLON.Vector3.Zero();
  12008. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12009. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12010. _this._isDirty = false;
  12011. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12012. _this._isDisposed = false;
  12013. _this._renderId = 0;
  12014. _this._intersectionsInProgress = new Array();
  12015. _this._isWorldMatrixFrozen = false;
  12016. _this._unIndexed = false;
  12017. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12018. if (collidedMesh === void 0) { collidedMesh = null; }
  12019. //TODO move this to the collision coordinator!
  12020. if (_this.getScene().workerCollisions)
  12021. newPosition.multiplyInPlace(_this._collider.radius);
  12022. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12023. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12024. _this.position.addInPlace(_this._diffPositionForCollisions);
  12025. }
  12026. if (collidedMesh) {
  12027. _this.onCollideObservable.notifyObservers(collidedMesh);
  12028. }
  12029. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12030. };
  12031. _this.getScene().addMesh(_this);
  12032. return _this;
  12033. }
  12034. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12035. get: function () {
  12036. return AbstractMesh._BILLBOARDMODE_NONE;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12042. get: function () {
  12043. return AbstractMesh._BILLBOARDMODE_X;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12049. get: function () {
  12050. return AbstractMesh._BILLBOARDMODE_Y;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12056. get: function () {
  12057. return AbstractMesh._BILLBOARDMODE_Z;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12063. get: function () {
  12064. return AbstractMesh._BILLBOARDMODE_ALL;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12070. /**
  12071. * Read-only : the number of facets in the mesh
  12072. */
  12073. get: function () {
  12074. return this._facetNb;
  12075. },
  12076. enumerable: true,
  12077. configurable: true
  12078. });
  12079. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12080. /**
  12081. * The number (integer) of subdivisions per axis in the partioning space
  12082. */
  12083. get: function () {
  12084. return this._partitioningSubdivisions;
  12085. },
  12086. set: function (nb) {
  12087. this._partitioningSubdivisions = nb;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12093. /**
  12094. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12095. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12096. */
  12097. get: function () {
  12098. return this._partitioningBBoxRatio;
  12099. },
  12100. set: function (ratio) {
  12101. this._partitioningBBoxRatio = ratio;
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12107. /**
  12108. * Read-only boolean : is the feature facetData enabled ?
  12109. */
  12110. get: function () {
  12111. return this._facetDataEnabled;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12117. set: function (callback) {
  12118. if (this._onCollideObserver) {
  12119. this.onCollideObservable.remove(this._onCollideObserver);
  12120. }
  12121. this._onCollideObserver = this.onCollideObservable.add(callback);
  12122. },
  12123. enumerable: true,
  12124. configurable: true
  12125. });
  12126. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12127. set: function (callback) {
  12128. if (this._onCollisionPositionChangeObserver) {
  12129. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12130. }
  12131. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12137. get: function () {
  12138. return this._collisionMask;
  12139. },
  12140. set: function (mask) {
  12141. this._collisionMask = !isNaN(mask) ? mask : -1;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12147. get: function () {
  12148. return this._collisionGroup;
  12149. },
  12150. set: function (mask) {
  12151. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12157. get: function () {
  12158. return this._skeleton;
  12159. },
  12160. set: function (value) {
  12161. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12162. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12163. }
  12164. if (value && value.needInitialSkinMatrix) {
  12165. value._registerMeshWithPoseMatrix(this);
  12166. }
  12167. this._skeleton = value;
  12168. if (!this._skeleton) {
  12169. this._bonesTransformMatrices = null;
  12170. }
  12171. },
  12172. enumerable: true,
  12173. configurable: true
  12174. });
  12175. /**
  12176. * Returns the string "AbstractMesh"
  12177. */
  12178. AbstractMesh.prototype.getClassName = function () {
  12179. return "AbstractMesh";
  12180. };
  12181. /**
  12182. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12183. */
  12184. AbstractMesh.prototype.toString = function (fullDetails) {
  12185. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12186. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12187. if (this._skeleton) {
  12188. ret += ", skeleton: " + this._skeleton.name;
  12189. }
  12190. if (fullDetails) {
  12191. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12192. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12193. }
  12194. return ret;
  12195. };
  12196. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12197. /**
  12198. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12199. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12200. * Default : (0.0, 0.0, 0.0)
  12201. */
  12202. get: function () {
  12203. return this._rotation;
  12204. },
  12205. set: function (newRotation) {
  12206. this._rotation = newRotation;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12212. /**
  12213. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12214. * Default : (1.0, 1.0, 1.0)
  12215. */
  12216. get: function () {
  12217. return this._scaling;
  12218. },
  12219. set: function (newScaling) {
  12220. this._scaling = newScaling;
  12221. if (this.physicsImpostor) {
  12222. this.physicsImpostor.forceUpdate();
  12223. }
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12229. /**
  12230. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12231. * It's null by default.
  12232. * 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)
  12233. */
  12234. get: function () {
  12235. return this._rotationQuaternion;
  12236. },
  12237. set: function (quaternion) {
  12238. this._rotationQuaternion = quaternion;
  12239. //reset the rotation vector.
  12240. if (quaternion && this.rotation.length()) {
  12241. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12242. }
  12243. },
  12244. enumerable: true,
  12245. configurable: true
  12246. });
  12247. // Methods
  12248. /**
  12249. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12250. * Returns the AbstractMesh.
  12251. */
  12252. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12253. this._poseMatrix.copyFrom(matrix);
  12254. return this;
  12255. };
  12256. /**
  12257. * Returns the mesh Pose matrix.
  12258. * Returned object : Matrix
  12259. */
  12260. AbstractMesh.prototype.getPoseMatrix = function () {
  12261. return this._poseMatrix;
  12262. };
  12263. /**
  12264. * Disables the mesh edger rendering mode.
  12265. * Returns the AbstractMesh.
  12266. */
  12267. AbstractMesh.prototype.disableEdgesRendering = function () {
  12268. if (this._edgesRenderer !== undefined) {
  12269. this._edgesRenderer.dispose();
  12270. this._edgesRenderer = undefined;
  12271. }
  12272. return this;
  12273. };
  12274. /**
  12275. * Enables the edge rendering mode on the mesh.
  12276. * This mode makes the mesh edges visible.
  12277. * Returns the AbstractMesh.
  12278. */
  12279. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12280. if (epsilon === void 0) { epsilon = 0.95; }
  12281. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12282. this.disableEdgesRendering();
  12283. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12284. return this;
  12285. };
  12286. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12287. /**
  12288. * Returns true if the mesh is blocked. Used by the class Mesh.
  12289. * Returns the boolean `false` by default.
  12290. */
  12291. get: function () {
  12292. return false;
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. /**
  12298. * Returns the mesh itself by default, used by the class Mesh.
  12299. * Returned type : AbstractMesh
  12300. */
  12301. AbstractMesh.prototype.getLOD = function (camera) {
  12302. return this;
  12303. };
  12304. /**
  12305. * Returns 0 by default, used by the class Mesh.
  12306. * Returns an integer.
  12307. */
  12308. AbstractMesh.prototype.getTotalVertices = function () {
  12309. return 0;
  12310. };
  12311. /**
  12312. * Returns null by default, used by the class Mesh.
  12313. * Returned type : integer array
  12314. */
  12315. AbstractMesh.prototype.getIndices = function () {
  12316. return null;
  12317. };
  12318. /**
  12319. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12320. * Returned type : float array or Float32Array
  12321. */
  12322. AbstractMesh.prototype.getVerticesData = function (kind) {
  12323. return null;
  12324. };
  12325. /** Returns false by default, used by the class Mesh.
  12326. * Returns a boolean
  12327. */
  12328. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12329. return false;
  12330. };
  12331. /**
  12332. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12333. * Returns a BoundingInfo
  12334. */
  12335. AbstractMesh.prototype.getBoundingInfo = function () {
  12336. if (this._masterMesh) {
  12337. return this._masterMesh.getBoundingInfo();
  12338. }
  12339. if (!this._boundingInfo) {
  12340. this._updateBoundingInfo();
  12341. }
  12342. return this._boundingInfo;
  12343. };
  12344. /**
  12345. * Sets a mesh new object BoundingInfo.
  12346. * Returns the AbstractMesh.
  12347. */
  12348. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12349. this._boundingInfo = boundingInfo;
  12350. return this;
  12351. };
  12352. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12353. get: function () {
  12354. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12355. },
  12356. enumerable: true,
  12357. configurable: true
  12358. });
  12359. AbstractMesh.prototype._preActivate = function () {
  12360. };
  12361. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12362. };
  12363. AbstractMesh.prototype._activate = function (renderId) {
  12364. this._renderId = renderId;
  12365. };
  12366. /**
  12367. * Returns the last update of the World matrix
  12368. * Returns a Matrix.
  12369. */
  12370. AbstractMesh.prototype.getWorldMatrix = function () {
  12371. if (this._masterMesh) {
  12372. return this._masterMesh.getWorldMatrix();
  12373. }
  12374. if (this._currentRenderId !== this.getScene().getRenderId()) {
  12375. this.computeWorldMatrix();
  12376. }
  12377. return this._worldMatrix;
  12378. };
  12379. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12380. /**
  12381. * Returns directly the last state of the mesh World matrix.
  12382. * A Matrix is returned.
  12383. */
  12384. get: function () {
  12385. return this._worldMatrix;
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12391. /**
  12392. * Returns the current mesh absolute position.
  12393. * Retuns a Vector3.
  12394. */
  12395. get: function () {
  12396. return this._absolutePosition;
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. /**
  12402. * Prevents the World matrix to be computed any longer.
  12403. * Returns the AbstractMesh.
  12404. */
  12405. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12406. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12407. this.computeWorldMatrix(true);
  12408. this._isWorldMatrixFrozen = true;
  12409. return this;
  12410. };
  12411. /**
  12412. * Allows back the World matrix computation.
  12413. * Returns the AbstractMesh.
  12414. */
  12415. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12416. this._isWorldMatrixFrozen = false;
  12417. this.computeWorldMatrix(true);
  12418. return this;
  12419. };
  12420. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12421. /**
  12422. * True if the World matrix has been frozen.
  12423. * Returns a boolean.
  12424. */
  12425. get: function () {
  12426. return this._isWorldMatrixFrozen;
  12427. },
  12428. enumerable: true,
  12429. configurable: true
  12430. });
  12431. /**
  12432. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12433. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12434. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12435. * The passed axis is also normalized.
  12436. * Returns the AbstractMesh.
  12437. */
  12438. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12439. axis.normalize();
  12440. if (!this.rotationQuaternion) {
  12441. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12442. this.rotation = BABYLON.Vector3.Zero();
  12443. }
  12444. var rotationQuaternion;
  12445. if (!space || space === BABYLON.Space.LOCAL) {
  12446. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12447. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12448. }
  12449. else {
  12450. if (this.parent) {
  12451. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12452. invertParentWorldMatrix.invert();
  12453. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12454. }
  12455. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12456. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12457. }
  12458. return this;
  12459. };
  12460. /**
  12461. * Translates the mesh along the axis vector for the passed distance in the given space.
  12462. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12463. * Returns the AbstractMesh.
  12464. */
  12465. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12466. var displacementVector = axis.scale(distance);
  12467. if (!space || space === BABYLON.Space.LOCAL) {
  12468. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12469. this.setPositionWithLocalVector(tempV3);
  12470. }
  12471. else {
  12472. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12473. }
  12474. return this;
  12475. };
  12476. /**
  12477. * Adds a rotation step to the mesh current rotation.
  12478. * x, y, z are Euler angles expressed in radians.
  12479. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12480. * This means this rotation is made in the mesh local space only.
  12481. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12482. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12483. * ```javascript
  12484. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12485. * ```
  12486. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12487. * 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.
  12488. * Returns the AbstractMesh.
  12489. */
  12490. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12491. var rotationQuaternion;
  12492. if (this.rotationQuaternion) {
  12493. rotationQuaternion = this.rotationQuaternion;
  12494. }
  12495. else {
  12496. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12497. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12498. }
  12499. var accumulation = BABYLON.Tmp.Quaternion[0];
  12500. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12501. rotationQuaternion.multiplyInPlace(accumulation);
  12502. if (!this.rotationQuaternion) {
  12503. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12504. }
  12505. return this;
  12506. };
  12507. /**
  12508. * Retuns the mesh absolute position in the World.
  12509. * Returns a Vector3.
  12510. */
  12511. AbstractMesh.prototype.getAbsolutePosition = function () {
  12512. this.computeWorldMatrix();
  12513. return this._absolutePosition;
  12514. };
  12515. /**
  12516. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12517. * Returns the AbstractMesh.
  12518. */
  12519. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12520. if (!absolutePosition) {
  12521. return;
  12522. }
  12523. var absolutePositionX;
  12524. var absolutePositionY;
  12525. var absolutePositionZ;
  12526. if (absolutePosition.x === undefined) {
  12527. if (arguments.length < 3) {
  12528. return;
  12529. }
  12530. absolutePositionX = arguments[0];
  12531. absolutePositionY = arguments[1];
  12532. absolutePositionZ = arguments[2];
  12533. }
  12534. else {
  12535. absolutePositionX = absolutePosition.x;
  12536. absolutePositionY = absolutePosition.y;
  12537. absolutePositionZ = absolutePosition.z;
  12538. }
  12539. if (this.parent) {
  12540. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12541. invertParentWorldMatrix.invert();
  12542. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12543. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12544. }
  12545. else {
  12546. this.position.x = absolutePositionX;
  12547. this.position.y = absolutePositionY;
  12548. this.position.z = absolutePositionZ;
  12549. }
  12550. return this;
  12551. };
  12552. // ================================== Point of View Movement =================================
  12553. /**
  12554. * Perform relative position change from the point of view of behind the front of the mesh.
  12555. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12556. * Supports definition of mesh facing forward or backward.
  12557. * @param {number} amountRight
  12558. * @param {number} amountUp
  12559. * @param {number} amountForward
  12560. *
  12561. * Returns the AbstractMesh.
  12562. */
  12563. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12564. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12565. return this;
  12566. };
  12567. /**
  12568. * Calculate relative position change from the point of view of behind the front of the mesh.
  12569. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12570. * Supports definition of mesh facing forward or backward.
  12571. * @param {number} amountRight
  12572. * @param {number} amountUp
  12573. * @param {number} amountForward
  12574. *
  12575. * Returns a new Vector3.
  12576. */
  12577. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12578. var rotMatrix = new BABYLON.Matrix();
  12579. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12580. rotQuaternion.toRotationMatrix(rotMatrix);
  12581. var translationDelta = BABYLON.Vector3.Zero();
  12582. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12583. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12584. return translationDelta;
  12585. };
  12586. // ================================== Point of View Rotation =================================
  12587. /**
  12588. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12589. * Supports definition of mesh facing forward or backward.
  12590. * @param {number} flipBack
  12591. * @param {number} twirlClockwise
  12592. * @param {number} tiltRight
  12593. *
  12594. * Returns the AbstractMesh.
  12595. */
  12596. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12597. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12598. return this;
  12599. };
  12600. /**
  12601. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12602. * Supports definition of mesh facing forward or backward.
  12603. * @param {number} flipBack
  12604. * @param {number} twirlClockwise
  12605. * @param {number} tiltRight
  12606. *
  12607. * Returns a new Vector3.
  12608. */
  12609. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12610. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12611. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12612. };
  12613. /**
  12614. * Sets a new pivot matrix to the mesh.
  12615. * Returns the AbstractMesh.
  12616. */
  12617. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12618. this._pivotMatrix = matrix;
  12619. this._cache.pivotMatrixUpdated = true;
  12620. return this;
  12621. };
  12622. /**
  12623. * Returns the mesh pivot matrix.
  12624. * Default : Identity.
  12625. * A Matrix is returned.
  12626. */
  12627. AbstractMesh.prototype.getPivotMatrix = function () {
  12628. return this._pivotMatrix;
  12629. };
  12630. AbstractMesh.prototype._isSynchronized = function () {
  12631. if (this._isDirty) {
  12632. return false;
  12633. }
  12634. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12635. return false;
  12636. if (this._cache.pivotMatrixUpdated) {
  12637. return false;
  12638. }
  12639. if (this.infiniteDistance) {
  12640. return false;
  12641. }
  12642. if (!this._cache.position.equals(this.position))
  12643. return false;
  12644. if (this.rotationQuaternion) {
  12645. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12646. return false;
  12647. }
  12648. if (!this._cache.rotation.equals(this.rotation))
  12649. return false;
  12650. if (!this._cache.scaling.equals(this.scaling))
  12651. return false;
  12652. return true;
  12653. };
  12654. AbstractMesh.prototype._initCache = function () {
  12655. _super.prototype._initCache.call(this);
  12656. this._cache.localMatrixUpdated = false;
  12657. this._cache.position = BABYLON.Vector3.Zero();
  12658. this._cache.scaling = BABYLON.Vector3.Zero();
  12659. this._cache.rotation = BABYLON.Vector3.Zero();
  12660. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12661. this._cache.billboardMode = -1;
  12662. };
  12663. AbstractMesh.prototype.markAsDirty = function (property) {
  12664. if (property === "rotation") {
  12665. this.rotationQuaternion = null;
  12666. }
  12667. this._currentRenderId = Number.MAX_VALUE;
  12668. this._isDirty = true;
  12669. return this;
  12670. };
  12671. /**
  12672. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12673. * Returns the AbstractMesh.
  12674. */
  12675. AbstractMesh.prototype._updateBoundingInfo = function () {
  12676. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12677. this._boundingInfo.update(this.worldMatrixFromCache);
  12678. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12679. return this;
  12680. };
  12681. /**
  12682. * Update a mesh's children BoundingInfo objects only.
  12683. * Returns the AbstractMesh.
  12684. */
  12685. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12686. if (!this.subMeshes) {
  12687. return;
  12688. }
  12689. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12690. var subMesh = this.subMeshes[subIndex];
  12691. if (!subMesh.IsGlobal) {
  12692. subMesh.updateBoundingInfo(matrix);
  12693. }
  12694. }
  12695. return this;
  12696. };
  12697. /**
  12698. * Computes the mesh World matrix and returns it.
  12699. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12700. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12701. * If the parameter `force`is set to `true`, the actual computation is done.
  12702. * Returns the mesh World Matrix.
  12703. */
  12704. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12705. if (this._isWorldMatrixFrozen) {
  12706. return this._worldMatrix;
  12707. }
  12708. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  12709. this._currentRenderId = this.getScene().getRenderId();
  12710. return this._worldMatrix;
  12711. }
  12712. this._cache.position.copyFrom(this.position);
  12713. this._cache.scaling.copyFrom(this.scaling);
  12714. this._cache.pivotMatrixUpdated = false;
  12715. this._cache.billboardMode = this.billboardMode;
  12716. this._currentRenderId = this.getScene().getRenderId();
  12717. this._isDirty = false;
  12718. // Scaling
  12719. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12720. // Rotation
  12721. //rotate, if quaternion is set and rotation was used
  12722. if (this.rotationQuaternion) {
  12723. var len = this.rotation.length();
  12724. if (len) {
  12725. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12726. this.rotation.copyFromFloats(0, 0, 0);
  12727. }
  12728. }
  12729. if (this.rotationQuaternion) {
  12730. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12731. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12732. }
  12733. else {
  12734. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12735. this._cache.rotation.copyFrom(this.rotation);
  12736. }
  12737. // Translation
  12738. if (this.infiniteDistance && !this.parent) {
  12739. var camera = this.getScene().activeCamera;
  12740. if (camera) {
  12741. var cameraWorldMatrix = camera.getWorldMatrix();
  12742. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12743. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12744. }
  12745. }
  12746. else {
  12747. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12748. }
  12749. // Composing transformations
  12750. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12751. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12752. // Mesh referal
  12753. var completeMeshReferalMatrix = BABYLON.Tmp.Matrix[6];
  12754. if (this._meshToBoneReferal && this.parent && this.parent.getWorldMatrix) {
  12755. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), completeMeshReferalMatrix);
  12756. }
  12757. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12758. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12759. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12760. // Need to decompose each rotation here
  12761. var currentPosition = BABYLON.Tmp.Vector3[3];
  12762. if (this.parent && this.parent.getWorldMatrix) {
  12763. if (this._meshToBoneReferal) {
  12764. BABYLON.Vector3.TransformCoordinatesToRef(this.position, completeMeshReferalMatrix, currentPosition);
  12765. }
  12766. else {
  12767. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12768. }
  12769. }
  12770. else {
  12771. currentPosition.copyFrom(this.position);
  12772. }
  12773. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12774. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12775. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12776. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12777. }
  12778. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12779. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12780. }
  12781. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12782. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12783. }
  12784. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12785. }
  12786. else {
  12787. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12788. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12789. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12790. }
  12791. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12792. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12793. }
  12794. // Local world
  12795. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12796. // Parent
  12797. if (this.parent && this.parent.getWorldMatrix) {
  12798. this._markSyncedWithParent();
  12799. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12800. if (this._meshToBoneReferal) {
  12801. BABYLON.Tmp.Matrix[5].copyFrom(completeMeshReferalMatrix);
  12802. }
  12803. else {
  12804. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12805. }
  12806. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12807. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12808. this._worldMatrix.copyFrom(this._localWorld);
  12809. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12810. }
  12811. else {
  12812. if (this._meshToBoneReferal) {
  12813. this._localWorld.multiplyToRef(completeMeshReferalMatrix, this._worldMatrix);
  12814. }
  12815. else {
  12816. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12817. }
  12818. }
  12819. }
  12820. else {
  12821. this._worldMatrix.copyFrom(this._localWorld);
  12822. }
  12823. // Bounding info
  12824. this._updateBoundingInfo();
  12825. // Absolute position
  12826. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12827. // Callbacks
  12828. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12829. if (!this._poseMatrix) {
  12830. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12831. }
  12832. return this._worldMatrix;
  12833. };
  12834. /**
  12835. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12836. * @param func: callback function to add
  12837. *
  12838. * Returns the AbstractMesh.
  12839. */
  12840. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12841. this.onAfterWorldMatrixUpdateObservable.add(func);
  12842. return this;
  12843. };
  12844. /**
  12845. * Removes a registered callback function.
  12846. * Returns the AbstractMesh.
  12847. */
  12848. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12849. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12850. return this;
  12851. };
  12852. /**
  12853. * Sets the mesh position in its local space.
  12854. * Returns the AbstractMesh.
  12855. */
  12856. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12857. this.computeWorldMatrix();
  12858. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12859. return this;
  12860. };
  12861. /**
  12862. * Returns the mesh position in the local space from the current World matrix values.
  12863. * Returns a new Vector3.
  12864. */
  12865. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12866. this.computeWorldMatrix();
  12867. var invLocalWorldMatrix = this._localWorld.clone();
  12868. invLocalWorldMatrix.invert();
  12869. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12870. };
  12871. /**
  12872. * Translates the mesh along the passed Vector3 in its local space.
  12873. * Returns the AbstractMesh.
  12874. */
  12875. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12876. this.computeWorldMatrix(true);
  12877. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12878. return this;
  12879. };
  12880. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12881. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12882. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12883. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12884. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12885. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12886. /// <returns>Mesh oriented towards targetMesh</returns>
  12887. if (yawCor === void 0) { yawCor = 0; }
  12888. if (pitchCor === void 0) { pitchCor = 0; }
  12889. if (rollCor === void 0) { rollCor = 0; }
  12890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12891. var dv = AbstractMesh._lookAtVectorCache;
  12892. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12893. targetPoint.subtractToRef(pos, dv);
  12894. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12895. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12896. var pitch = Math.atan2(dv.y, len);
  12897. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12898. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12899. return this;
  12900. };
  12901. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12902. this._meshToBoneReferal = affectedMesh;
  12903. this.parent = bone;
  12904. if (bone.getWorldMatrix().determinant() < 0) {
  12905. this.scalingDeterminant *= -1;
  12906. }
  12907. return this;
  12908. };
  12909. AbstractMesh.prototype.detachFromBone = function () {
  12910. if (this.parent.getWorldMatrix().determinant() < 0) {
  12911. this.scalingDeterminant *= -1;
  12912. }
  12913. this._meshToBoneReferal = null;
  12914. this.parent = null;
  12915. return this;
  12916. };
  12917. /**
  12918. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12919. * A mesh is in the frustum if its bounding box intersects the frustum.
  12920. * Boolean returned.
  12921. */
  12922. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12923. return this._boundingInfo.isInFrustum(frustumPlanes);
  12924. };
  12925. /**
  12926. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12927. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12928. * Boolean returned.
  12929. */
  12930. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12931. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12932. ;
  12933. };
  12934. /**
  12935. * True if the mesh intersects another mesh or a SolidParticle object.
  12936. * 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)
  12937. * Returns a boolean.
  12938. */
  12939. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12940. if (!this._boundingInfo || !mesh._boundingInfo) {
  12941. return false;
  12942. }
  12943. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12944. };
  12945. /**
  12946. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12947. * Returns a boolean.
  12948. */
  12949. AbstractMesh.prototype.intersectsPoint = function (point) {
  12950. if (!this._boundingInfo) {
  12951. return false;
  12952. }
  12953. return this._boundingInfo.intersectsPoint(point);
  12954. };
  12955. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12956. return this.physicsImpostor;
  12957. };
  12958. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12959. if (!camera) {
  12960. camera = this.getScene().activeCamera;
  12961. }
  12962. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12963. };
  12964. /**
  12965. * Returns the distance from the mesh to the active camera.
  12966. * Returns a float.
  12967. */
  12968. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12969. if (!camera) {
  12970. camera = this.getScene().activeCamera;
  12971. }
  12972. return this.absolutePosition.subtract(camera.position).length();
  12973. };
  12974. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12975. if (!this.physicsImpostor) {
  12976. return;
  12977. }
  12978. this.physicsImpostor.applyImpulse(force, contactPoint);
  12979. return this;
  12980. };
  12981. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12982. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12983. return;
  12984. }
  12985. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12986. mainPivot: pivot1,
  12987. connectedPivot: pivot2,
  12988. nativeParams: options
  12989. });
  12990. return this;
  12991. };
  12992. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12993. // Collisions
  12994. /**
  12995. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12996. * Default `false`.
  12997. */
  12998. get: function () {
  12999. return this._checkCollisions;
  13000. },
  13001. set: function (collisionEnabled) {
  13002. this._checkCollisions = collisionEnabled;
  13003. if (this.getScene().workerCollisions) {
  13004. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13005. }
  13006. },
  13007. enumerable: true,
  13008. configurable: true
  13009. });
  13010. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13011. var globalPosition = this.getAbsolutePosition();
  13012. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13013. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13014. this._collider.radius = this.ellipsoid;
  13015. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13016. return this;
  13017. };
  13018. // Submeshes octree
  13019. /**
  13020. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13021. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13022. * Returns an Octree of submeshes.
  13023. */
  13024. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13025. if (maxCapacity === void 0) { maxCapacity = 64; }
  13026. if (maxDepth === void 0) { maxDepth = 2; }
  13027. if (!this._submeshesOctree) {
  13028. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13029. }
  13030. this.computeWorldMatrix(true);
  13031. // Update octree
  13032. var bbox = this.getBoundingInfo().boundingBox;
  13033. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13034. return this._submeshesOctree;
  13035. };
  13036. // Collisions
  13037. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13038. this._generatePointsArray();
  13039. // Transformation
  13040. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13041. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13042. subMesh._lastColliderWorldVertices = [];
  13043. subMesh._trianglePlanes = [];
  13044. var start = subMesh.verticesStart;
  13045. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13046. for (var i = start; i < end; i++) {
  13047. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13048. }
  13049. }
  13050. // Collide
  13051. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13052. if (collider.collisionFound) {
  13053. collider.collidedMesh = this;
  13054. }
  13055. return this;
  13056. };
  13057. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13058. var subMeshes;
  13059. var len;
  13060. // Octrees
  13061. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13062. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13063. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13064. len = intersections.length;
  13065. subMeshes = intersections.data;
  13066. }
  13067. else {
  13068. subMeshes = this.subMeshes;
  13069. len = subMeshes.length;
  13070. }
  13071. for (var index = 0; index < len; index++) {
  13072. var subMesh = subMeshes[index];
  13073. // Bounding test
  13074. if (len > 1 && !subMesh._checkCollision(collider))
  13075. continue;
  13076. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13077. }
  13078. return this;
  13079. };
  13080. AbstractMesh.prototype._checkCollision = function (collider) {
  13081. // Bounding box test
  13082. if (!this._boundingInfo._checkCollision(collider))
  13083. return this;
  13084. // Transformation matrix
  13085. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13086. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13087. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13088. return this;
  13089. };
  13090. // Picking
  13091. AbstractMesh.prototype._generatePointsArray = function () {
  13092. return false;
  13093. };
  13094. /**
  13095. * Checks if the passed Ray intersects with the mesh.
  13096. * Returns an object PickingInfo.
  13097. */
  13098. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13099. var pickingInfo = new BABYLON.PickingInfo();
  13100. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13101. return pickingInfo;
  13102. }
  13103. if (!this._generatePointsArray()) {
  13104. return pickingInfo;
  13105. }
  13106. var intersectInfo = null;
  13107. // Octrees
  13108. var subMeshes;
  13109. var len;
  13110. if (this._submeshesOctree && this.useOctreeForPicking) {
  13111. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13112. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13113. len = intersections.length;
  13114. subMeshes = intersections.data;
  13115. }
  13116. else {
  13117. subMeshes = this.subMeshes;
  13118. len = subMeshes.length;
  13119. }
  13120. for (var index = 0; index < len; index++) {
  13121. var subMesh = subMeshes[index];
  13122. // Bounding test
  13123. if (len > 1 && !subMesh.canIntersects(ray))
  13124. continue;
  13125. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13126. if (currentIntersectInfo) {
  13127. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13128. intersectInfo = currentIntersectInfo;
  13129. intersectInfo.subMeshId = index;
  13130. if (fastCheck) {
  13131. break;
  13132. }
  13133. }
  13134. }
  13135. }
  13136. if (intersectInfo) {
  13137. // Get picked point
  13138. var world = this.getWorldMatrix();
  13139. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13140. var direction = ray.direction.clone();
  13141. direction = direction.scale(intersectInfo.distance);
  13142. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13143. var pickedPoint = worldOrigin.add(worldDirection);
  13144. // Return result
  13145. pickingInfo.hit = true;
  13146. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13147. pickingInfo.pickedPoint = pickedPoint;
  13148. pickingInfo.pickedMesh = this;
  13149. pickingInfo.bu = intersectInfo.bu;
  13150. pickingInfo.bv = intersectInfo.bv;
  13151. pickingInfo.faceId = intersectInfo.faceId;
  13152. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13153. return pickingInfo;
  13154. }
  13155. return pickingInfo;
  13156. };
  13157. /**
  13158. * Clones the mesh, used by the class Mesh.
  13159. * Just returns `null` for an AbstractMesh.
  13160. */
  13161. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13162. return null;
  13163. };
  13164. /**
  13165. * Disposes all the mesh submeshes.
  13166. * Returns the AbstractMesh.
  13167. */
  13168. AbstractMesh.prototype.releaseSubMeshes = function () {
  13169. if (this.subMeshes) {
  13170. while (this.subMeshes.length) {
  13171. this.subMeshes[0].dispose();
  13172. }
  13173. }
  13174. else {
  13175. this.subMeshes = new Array();
  13176. }
  13177. return this;
  13178. };
  13179. /**
  13180. * Disposes the AbstractMesh.
  13181. * Some internal references are kept for further use.
  13182. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13183. * Returns nothing.
  13184. */
  13185. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13186. var _this = this;
  13187. var index;
  13188. // Action manager
  13189. if (this.actionManager) {
  13190. this.actionManager.dispose();
  13191. this.actionManager = null;
  13192. }
  13193. // Skeleton
  13194. this.skeleton = null;
  13195. // Animations
  13196. this.getScene().stopAnimation(this);
  13197. // Physics
  13198. if (this.physicsImpostor) {
  13199. this.physicsImpostor.dispose();
  13200. }
  13201. // Intersections in progress
  13202. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13203. var other = this._intersectionsInProgress[index];
  13204. var pos = other._intersectionsInProgress.indexOf(this);
  13205. other._intersectionsInProgress.splice(pos, 1);
  13206. }
  13207. this._intersectionsInProgress = [];
  13208. // Lights
  13209. var lights = this.getScene().lights;
  13210. lights.forEach(function (light) {
  13211. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13212. if (meshIndex !== -1) {
  13213. light.includedOnlyMeshes.splice(meshIndex, 1);
  13214. }
  13215. meshIndex = light.excludedMeshes.indexOf(_this);
  13216. if (meshIndex !== -1) {
  13217. light.excludedMeshes.splice(meshIndex, 1);
  13218. }
  13219. // Shadow generators
  13220. var generator = light.getShadowGenerator();
  13221. if (generator) {
  13222. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13223. if (meshIndex !== -1) {
  13224. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13225. }
  13226. }
  13227. });
  13228. // Edges
  13229. if (this._edgesRenderer) {
  13230. this._edgesRenderer.dispose();
  13231. this._edgesRenderer = null;
  13232. }
  13233. // SubMeshes
  13234. if (this.getClassName() !== "InstancedMesh") {
  13235. this.releaseSubMeshes();
  13236. }
  13237. // Engine
  13238. this.getScene().getEngine().wipeCaches();
  13239. // Remove from scene
  13240. this.getScene().removeMesh(this);
  13241. if (!doNotRecurse) {
  13242. // Particles
  13243. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13244. if (this.getScene().particleSystems[index].emitter === this) {
  13245. this.getScene().particleSystems[index].dispose();
  13246. index--;
  13247. }
  13248. }
  13249. // Children
  13250. var objects = this.getDescendants(true);
  13251. for (index = 0; index < objects.length; index++) {
  13252. objects[index].dispose();
  13253. }
  13254. }
  13255. else {
  13256. var childMeshes = this.getChildMeshes(true);
  13257. for (index = 0; index < childMeshes.length; index++) {
  13258. var child = childMeshes[index];
  13259. child.parent = null;
  13260. child.computeWorldMatrix(true);
  13261. }
  13262. }
  13263. // facet data
  13264. if (this._facetDataEnabled) {
  13265. this.disableFacetData();
  13266. }
  13267. this.onAfterWorldMatrixUpdateObservable.clear();
  13268. this.onCollideObservable.clear();
  13269. this.onCollisionPositionChangeObservable.clear();
  13270. this._isDisposed = true;
  13271. _super.prototype.dispose.call(this);
  13272. };
  13273. /**
  13274. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13275. * This Vector3 is expressed in the World space.
  13276. */
  13277. AbstractMesh.prototype.getDirection = function (localAxis) {
  13278. var result = BABYLON.Vector3.Zero();
  13279. this.getDirectionToRef(localAxis, result);
  13280. return result;
  13281. };
  13282. /**
  13283. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13284. * localAxis is expressed in the mesh local space.
  13285. * result is computed in the Wordl space from the mesh World matrix.
  13286. * Returns the AbstractMesh.
  13287. */
  13288. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13289. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13290. return this;
  13291. };
  13292. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13293. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13294. if (this.getScene().getRenderId() == 0) {
  13295. this.computeWorldMatrix(true);
  13296. }
  13297. var wm = this.getWorldMatrix();
  13298. if (space == BABYLON.Space.WORLD) {
  13299. var tmat = BABYLON.Tmp.Matrix[0];
  13300. wm.invertToRef(tmat);
  13301. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13302. }
  13303. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13304. this._pivotMatrix.m[12] = -point.x;
  13305. this._pivotMatrix.m[13] = -point.y;
  13306. this._pivotMatrix.m[14] = -point.z;
  13307. this._cache.pivotMatrixUpdated = true;
  13308. return this;
  13309. };
  13310. /**
  13311. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13312. */
  13313. AbstractMesh.prototype.getPivotPoint = function () {
  13314. var point = BABYLON.Vector3.Zero();
  13315. this.getPivotPointToRef(point);
  13316. return point;
  13317. };
  13318. /**
  13319. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13320. * Returns the AbstractMesh.
  13321. */
  13322. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13323. result.x = -this._pivotMatrix.m[12];
  13324. result.y = -this._pivotMatrix.m[13];
  13325. result.z = -this._pivotMatrix.m[14];
  13326. return this;
  13327. };
  13328. /**
  13329. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13330. */
  13331. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13332. var point = BABYLON.Vector3.Zero();
  13333. this.getAbsolutePivotPointToRef(point);
  13334. return point;
  13335. };
  13336. /**
  13337. * Defines the passed mesh as the parent of the current mesh.
  13338. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13339. * Returns the AbstractMesh.
  13340. */
  13341. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13342. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13343. var child = this;
  13344. var parent = mesh;
  13345. if (mesh == null) {
  13346. if (child.parent && keepWorldPositionRotation) {
  13347. var rotation = BABYLON.Tmp.Quaternion[0];
  13348. var position = BABYLON.Tmp.Vector3[0];
  13349. var scale = BABYLON.Tmp.Vector3[1];
  13350. child.getWorldMatrix().decompose(scale, rotation, position);
  13351. if (child.rotationQuaternion) {
  13352. child.rotationQuaternion.copyFrom(rotation);
  13353. }
  13354. else {
  13355. rotation.toEulerAnglesToRef(child.rotation);
  13356. }
  13357. child.position.x = position.x;
  13358. child.position.y = position.y;
  13359. child.position.z = position.z;
  13360. }
  13361. }
  13362. else {
  13363. if (keepWorldPositionRotation) {
  13364. var rotation = BABYLON.Tmp.Quaternion[0];
  13365. var position = BABYLON.Tmp.Vector3[0];
  13366. var scale = BABYLON.Tmp.Vector3[1];
  13367. var m1 = BABYLON.Tmp.Matrix[0];
  13368. var m2 = BABYLON.Tmp.Matrix[1];
  13369. parent.getWorldMatrix().decompose(scale, rotation, position);
  13370. rotation.toRotationMatrix(m1);
  13371. m2.setTranslation(position);
  13372. m2.multiplyToRef(m1, m1);
  13373. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13374. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13375. m.decompose(scale, rotation, position);
  13376. if (child.rotationQuaternion) {
  13377. child.rotationQuaternion.copyFrom(rotation);
  13378. }
  13379. else {
  13380. rotation.toEulerAnglesToRef(child.rotation);
  13381. }
  13382. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13383. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13384. m.decompose(scale, rotation, position);
  13385. child.position.x = position.x;
  13386. child.position.y = position.y;
  13387. child.position.z = position.z;
  13388. }
  13389. }
  13390. child.parent = parent;
  13391. return this;
  13392. };
  13393. /**
  13394. * Adds the passed mesh as a child to the current mesh.
  13395. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13396. * Returns the AbstractMesh.
  13397. */
  13398. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13399. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13400. mesh.setParent(this, keepWorldPositionRotation);
  13401. return this;
  13402. };
  13403. /**
  13404. * Removes the passed mesh from the current mesh children list.
  13405. * Returns the AbstractMesh.
  13406. */
  13407. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13408. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13409. mesh.setParent(null, keepWorldPositionRotation);
  13410. return this;
  13411. };
  13412. /**
  13413. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13414. * Returns the AbstractMesh.
  13415. */
  13416. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13417. result.x = this._pivotMatrix.m[12];
  13418. result.y = this._pivotMatrix.m[13];
  13419. result.z = this._pivotMatrix.m[14];
  13420. this.getPivotPointToRef(result);
  13421. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13422. return this;
  13423. };
  13424. // Facet data
  13425. /**
  13426. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13427. * Returns the AbstractMesh.
  13428. */
  13429. AbstractMesh.prototype._initFacetData = function () {
  13430. if (!this._facetNormals) {
  13431. this._facetNormals = new Array();
  13432. }
  13433. if (!this._facetPositions) {
  13434. this._facetPositions = new Array();
  13435. }
  13436. if (!this._facetPartitioning) {
  13437. this._facetPartitioning = new Array();
  13438. }
  13439. this._facetNb = this.getIndices().length / 3;
  13440. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13441. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13442. for (var f = 0; f < this._facetNb; f++) {
  13443. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13444. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13445. }
  13446. this._facetDataEnabled = true;
  13447. return this;
  13448. };
  13449. /**
  13450. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13451. * This method can be called within the render loop.
  13452. * 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.
  13453. * Returns the AbstractMesh.
  13454. */
  13455. AbstractMesh.prototype.updateFacetData = function () {
  13456. if (!this._facetDataEnabled) {
  13457. this._initFacetData();
  13458. }
  13459. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13460. var indices = this.getIndices();
  13461. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13462. var bInfo = this.getBoundingInfo();
  13463. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13464. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13465. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13466. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13467. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13468. this._subDiv.max = this._partitioningSubdivisions;
  13469. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13470. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13471. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13472. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13473. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13474. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13475. // set the parameters for ComputeNormals()
  13476. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13477. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13478. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13479. this._facetParameters.bInfo = bInfo;
  13480. this._facetParameters.bbSize = this._bbSize;
  13481. this._facetParameters.subDiv = this._subDiv;
  13482. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13483. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13484. return this;
  13485. };
  13486. /**
  13487. * Returns the facetLocalNormals array.
  13488. * The normals are expressed in the mesh local space.
  13489. */
  13490. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13491. if (!this._facetNormals) {
  13492. this.updateFacetData();
  13493. }
  13494. return this._facetNormals;
  13495. };
  13496. /**
  13497. * Returns the facetLocalPositions array.
  13498. * The facet positions are expressed in the mesh local space.
  13499. */
  13500. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13501. if (!this._facetPositions) {
  13502. this.updateFacetData();
  13503. }
  13504. return this._facetPositions;
  13505. };
  13506. /**
  13507. * Returns the facetLocalPartioning array.
  13508. */
  13509. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13510. if (!this._facetPartitioning) {
  13511. this.updateFacetData();
  13512. }
  13513. return this._facetPartitioning;
  13514. };
  13515. /**
  13516. * Returns the i-th facet position in the world system.
  13517. * This method allocates a new Vector3 per call.
  13518. */
  13519. AbstractMesh.prototype.getFacetPosition = function (i) {
  13520. var pos = BABYLON.Vector3.Zero();
  13521. this.getFacetPositionToRef(i, pos);
  13522. return pos;
  13523. };
  13524. /**
  13525. * Sets the reference Vector3 with the i-th facet position in the world system.
  13526. * Returns the AbstractMesh.
  13527. */
  13528. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13529. var localPos = (this.getFacetLocalPositions())[i];
  13530. var world = this.getWorldMatrix();
  13531. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13532. return this;
  13533. };
  13534. /**
  13535. * Returns the i-th facet normal in the world system.
  13536. * This method allocates a new Vector3 per call.
  13537. */
  13538. AbstractMesh.prototype.getFacetNormal = function (i) {
  13539. var norm = BABYLON.Vector3.Zero();
  13540. this.getFacetNormalToRef(i, norm);
  13541. return norm;
  13542. };
  13543. /**
  13544. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13545. * Returns the AbstractMesh.
  13546. */
  13547. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13548. var localNorm = (this.getFacetLocalNormals())[i];
  13549. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13550. return this;
  13551. };
  13552. /**
  13553. * 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).
  13554. */
  13555. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13556. var bInfo = this.getBoundingInfo();
  13557. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13558. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13559. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13560. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13561. return null;
  13562. }
  13563. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13564. };
  13565. /**
  13566. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13567. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13568. * 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.
  13569. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13570. * 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.
  13571. */
  13572. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13573. if (checkFace === void 0) { checkFace = false; }
  13574. if (facing === void 0) { facing = true; }
  13575. var world = this.getWorldMatrix();
  13576. var invMat = BABYLON.Tmp.Matrix[5];
  13577. world.invertToRef(invMat);
  13578. var invVect = BABYLON.Tmp.Vector3[8];
  13579. var closest = null;
  13580. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13581. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13582. if (projected) {
  13583. // tranform the local computed projected vector to world coordinates
  13584. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13585. }
  13586. return closest;
  13587. };
  13588. /**
  13589. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13590. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13591. * 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.
  13592. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13593. * 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.
  13594. */
  13595. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13596. if (checkFace === void 0) { checkFace = false; }
  13597. if (facing === void 0) { facing = true; }
  13598. var closest = null;
  13599. var tmpx = 0.0;
  13600. var tmpy = 0.0;
  13601. var tmpz = 0.0;
  13602. var d = 0.0; // tmp dot facet normal * facet position
  13603. var t0 = 0.0;
  13604. var projx = 0.0;
  13605. var projy = 0.0;
  13606. var projz = 0.0;
  13607. // Get all the facets in the same partitioning block than (x, y, z)
  13608. var facetPositions = this.getFacetLocalPositions();
  13609. var facetNormals = this.getFacetLocalNormals();
  13610. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13611. if (!facetsInBlock) {
  13612. return null;
  13613. }
  13614. // Get the closest facet to (x, y, z)
  13615. var shortest = Number.MAX_VALUE; // init distance vars
  13616. var tmpDistance = shortest;
  13617. var fib; // current facet in the block
  13618. var norm; // current facet normal
  13619. var p0; // current facet barycenter position
  13620. // loop on all the facets in the current partitioning block
  13621. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13622. fib = facetsInBlock[idx];
  13623. norm = facetNormals[fib];
  13624. p0 = facetPositions[fib];
  13625. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13626. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13627. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13628. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13629. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13630. projx = x + norm.x * t0;
  13631. projy = y + norm.y * t0;
  13632. projz = z + norm.z * t0;
  13633. tmpx = projx - x;
  13634. tmpy = projy - y;
  13635. tmpz = projz - z;
  13636. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13637. if (tmpDistance < shortest) {
  13638. shortest = tmpDistance;
  13639. closest = fib;
  13640. if (projected) {
  13641. projected.x = projx;
  13642. projected.y = projy;
  13643. projected.z = projz;
  13644. }
  13645. }
  13646. }
  13647. }
  13648. return closest;
  13649. };
  13650. /**
  13651. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13652. */
  13653. AbstractMesh.prototype.getFacetDataParameters = function () {
  13654. return this._facetParameters;
  13655. };
  13656. /**
  13657. * Disables the feature FacetData and frees the related memory.
  13658. * Returns the AbstractMesh.
  13659. */
  13660. AbstractMesh.prototype.disableFacetData = function () {
  13661. if (this._facetDataEnabled) {
  13662. this._facetDataEnabled = false;
  13663. this._facetPositions = null;
  13664. this._facetNormals = null;
  13665. this._facetPartitioning = null;
  13666. this._facetParameters = null;
  13667. }
  13668. return this;
  13669. };
  13670. return AbstractMesh;
  13671. }(BABYLON.Node));
  13672. // Statics
  13673. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13674. AbstractMesh._BILLBOARDMODE_X = 1;
  13675. AbstractMesh._BILLBOARDMODE_Y = 2;
  13676. AbstractMesh._BILLBOARDMODE_Z = 4;
  13677. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13678. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13679. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13680. BABYLON.AbstractMesh = AbstractMesh;
  13681. })(BABYLON || (BABYLON = {}));
  13682. //# sourceMappingURL=babylon.abstractMesh.js.map
  13683. var BABYLON;
  13684. (function (BABYLON) {
  13685. var Light = (function (_super) {
  13686. __extends(Light, _super);
  13687. /**
  13688. * Creates a Light object in the scene.
  13689. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13690. */
  13691. function Light(name, scene) {
  13692. var _this = _super.call(this, name, scene) || this;
  13693. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13694. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13695. _this.intensity = 1.0;
  13696. _this.range = Number.MAX_VALUE;
  13697. _this.includeOnlyWithLayerMask = 0;
  13698. _this.includedOnlyMeshes = new Array();
  13699. _this.excludedMeshes = new Array();
  13700. _this.excludeWithLayerMask = 0;
  13701. _this.lightmapMode = 0;
  13702. // PBR Properties.
  13703. _this.radius = 0.00001;
  13704. _this._excludedMeshesIds = new Array();
  13705. _this._includedOnlyMeshesIds = new Array();
  13706. _this.getScene().addLight(_this);
  13707. return _this;
  13708. }
  13709. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13710. /**
  13711. * If every light affecting the material is in this lightmapMode,
  13712. * material.lightmapTexture adds or multiplies
  13713. * (depends on material.useLightmapAsShadowmap)
  13714. * after every other light calculations.
  13715. */
  13716. get: function () {
  13717. return Light._LIGHTMAP_DEFAULT;
  13718. },
  13719. enumerable: true,
  13720. configurable: true
  13721. });
  13722. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13723. /**
  13724. * material.lightmapTexture as only diffuse lighting from this light
  13725. * adds pnly specular lighting from this light
  13726. * adds dynamic shadows
  13727. */
  13728. get: function () {
  13729. return Light._LIGHTMAP_SPECULAR;
  13730. },
  13731. enumerable: true,
  13732. configurable: true
  13733. });
  13734. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13735. /**
  13736. * material.lightmapTexture as only lighting
  13737. * no light calculation from this light
  13738. * only adds dynamic shadows from this light
  13739. */
  13740. get: function () {
  13741. return Light._LIGHTMAP_SHADOWSONLY;
  13742. },
  13743. enumerable: true,
  13744. configurable: true
  13745. });
  13746. /**
  13747. * Returns the string "Light".
  13748. */
  13749. Light.prototype.getClassName = function () {
  13750. return "Light";
  13751. };
  13752. /**
  13753. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13754. */
  13755. Light.prototype.toString = function (fullDetails) {
  13756. var ret = "Name: " + this.name;
  13757. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13758. if (this.animations) {
  13759. for (var i = 0; i < this.animations.length; i++) {
  13760. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13761. }
  13762. }
  13763. if (fullDetails) {
  13764. }
  13765. return ret;
  13766. };
  13767. /**
  13768. * Returns the Light associated shadow generator.
  13769. */
  13770. Light.prototype.getShadowGenerator = function () {
  13771. return this._shadowGenerator;
  13772. };
  13773. /**
  13774. * Returns a Vector3, the absolute light position in the World.
  13775. */
  13776. Light.prototype.getAbsolutePosition = function () {
  13777. return BABYLON.Vector3.Zero();
  13778. };
  13779. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13780. };
  13781. Light.prototype._getWorldMatrix = function () {
  13782. return BABYLON.Matrix.Identity();
  13783. };
  13784. /**
  13785. * Boolean : True if the light will affect the passed mesh.
  13786. */
  13787. Light.prototype.canAffectMesh = function (mesh) {
  13788. if (!mesh) {
  13789. return true;
  13790. }
  13791. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13792. return false;
  13793. }
  13794. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13795. return false;
  13796. }
  13797. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13798. return false;
  13799. }
  13800. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13801. return false;
  13802. }
  13803. return true;
  13804. };
  13805. /**
  13806. * Returns the light World matrix.
  13807. */
  13808. Light.prototype.getWorldMatrix = function () {
  13809. this._currentRenderId = this.getScene().getRenderId();
  13810. var worldMatrix = this._getWorldMatrix();
  13811. if (this.parent && this.parent.getWorldMatrix) {
  13812. if (!this._parentedWorldMatrix) {
  13813. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13814. }
  13815. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13816. this._markSyncedWithParent();
  13817. return this._parentedWorldMatrix;
  13818. }
  13819. return worldMatrix;
  13820. };
  13821. /**
  13822. * Disposes the light.
  13823. */
  13824. Light.prototype.dispose = function () {
  13825. if (this._shadowGenerator) {
  13826. this._shadowGenerator.dispose();
  13827. this._shadowGenerator = null;
  13828. }
  13829. // Animations
  13830. this.getScene().stopAnimation(this);
  13831. // Remove from scene
  13832. this.getScene().removeLight(this);
  13833. _super.prototype.dispose.call(this);
  13834. };
  13835. /**
  13836. * Returns the light type ID (integer).
  13837. */
  13838. Light.prototype.getTypeID = function () {
  13839. return 0;
  13840. };
  13841. /**
  13842. * Returns a new Light object, named "name", from the current one.
  13843. */
  13844. Light.prototype.clone = function (name) {
  13845. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13846. };
  13847. /**
  13848. * Serializes the current light into a Serialization object.
  13849. * Returns the serialized object.
  13850. */
  13851. Light.prototype.serialize = function () {
  13852. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13853. // Type
  13854. serializationObject.type = this.getTypeID();
  13855. // Parent
  13856. if (this.parent) {
  13857. serializationObject.parentId = this.parent.id;
  13858. }
  13859. // Inclusion / exclusions
  13860. if (this.excludedMeshes.length > 0) {
  13861. serializationObject.excludedMeshesIds = [];
  13862. this.excludedMeshes.forEach(function (mesh) {
  13863. serializationObject.excludedMeshesIds.push(mesh.id);
  13864. });
  13865. }
  13866. if (this.includedOnlyMeshes.length > 0) {
  13867. serializationObject.includedOnlyMeshesIds = [];
  13868. this.includedOnlyMeshes.forEach(function (mesh) {
  13869. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13870. });
  13871. }
  13872. // Animations
  13873. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13874. serializationObject.ranges = this.serializeAnimationRanges();
  13875. return serializationObject;
  13876. };
  13877. /**
  13878. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13879. * This new light is named "name" and added to the passed scene.
  13880. */
  13881. Light.GetConstructorFromName = function (type, name, scene) {
  13882. switch (type) {
  13883. case 0:
  13884. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13885. case 1:
  13886. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13887. case 2:
  13888. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13889. case 3:
  13890. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13891. }
  13892. };
  13893. /**
  13894. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13895. */
  13896. Light.Parse = function (parsedLight, scene) {
  13897. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13898. // Inclusion / exclusions
  13899. if (parsedLight.excludedMeshesIds) {
  13900. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13901. }
  13902. if (parsedLight.includedOnlyMeshesIds) {
  13903. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13904. }
  13905. // Parent
  13906. if (parsedLight.parentId) {
  13907. light._waitingParentId = parsedLight.parentId;
  13908. }
  13909. // Animations
  13910. if (parsedLight.animations) {
  13911. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13912. var parsedAnimation = parsedLight.animations[animationIndex];
  13913. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13914. }
  13915. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13916. }
  13917. if (parsedLight.autoAnimate) {
  13918. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13919. }
  13920. return light;
  13921. };
  13922. return Light;
  13923. }(BABYLON.Node));
  13924. //lightmapMode Consts
  13925. Light._LIGHTMAP_DEFAULT = 0;
  13926. Light._LIGHTMAP_SPECULAR = 1;
  13927. Light._LIGHTMAP_SHADOWSONLY = 2;
  13928. __decorate([
  13929. BABYLON.serializeAsColor3()
  13930. ], Light.prototype, "diffuse", void 0);
  13931. __decorate([
  13932. BABYLON.serializeAsColor3()
  13933. ], Light.prototype, "specular", void 0);
  13934. __decorate([
  13935. BABYLON.serialize()
  13936. ], Light.prototype, "intensity", void 0);
  13937. __decorate([
  13938. BABYLON.serialize()
  13939. ], Light.prototype, "range", void 0);
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  13943. __decorate([
  13944. BABYLON.serialize()
  13945. ], Light.prototype, "excludeWithLayerMask", void 0);
  13946. __decorate([
  13947. BABYLON.serialize()
  13948. ], Light.prototype, "lightmapMode", void 0);
  13949. __decorate([
  13950. BABYLON.serialize()
  13951. ], Light.prototype, "radius", void 0);
  13952. BABYLON.Light = Light;
  13953. })(BABYLON || (BABYLON = {}));
  13954. //# sourceMappingURL=babylon.light.js.map
  13955. var BABYLON;
  13956. (function (BABYLON) {
  13957. var PointLight = (function (_super) {
  13958. __extends(PointLight, _super);
  13959. /**
  13960. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  13961. * A PointLight emits the light in every direction.
  13962. * It can cast shadows.
  13963. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  13964. * ```javascript
  13965. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  13966. * ```
  13967. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13968. */
  13969. function PointLight(name, position, scene) {
  13970. var _this = _super.call(this, name, scene) || this;
  13971. _this.position = position;
  13972. return _this;
  13973. }
  13974. /**
  13975. * Returns the string "PointLight"
  13976. */
  13977. PointLight.prototype.getClassName = function () {
  13978. return "PointLight";
  13979. };
  13980. /**
  13981. * Returns a Vector3, the PointLight absolute position in the World.
  13982. */
  13983. PointLight.prototype.getAbsolutePosition = function () {
  13984. return this.transformedPosition ? this.transformedPosition : this.position;
  13985. };
  13986. /**
  13987. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  13988. */
  13989. PointLight.prototype.computeTransformedPosition = function () {
  13990. if (this.parent && this.parent.getWorldMatrix) {
  13991. if (!this.transformedPosition) {
  13992. this.transformedPosition = BABYLON.Vector3.Zero();
  13993. }
  13994. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  13995. return true;
  13996. }
  13997. return false;
  13998. };
  13999. /**
  14000. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14001. * Returns the PointLight.
  14002. */
  14003. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14004. if (this.parent && this.parent.getWorldMatrix) {
  14005. this.computeTransformedPosition();
  14006. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14007. return this;
  14008. }
  14009. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14010. return this;
  14011. };
  14012. /**
  14013. * Boolean : returns true by default.
  14014. */
  14015. PointLight.prototype.needCube = function () {
  14016. return true;
  14017. };
  14018. /**
  14019. * Boolean : returns false by default.
  14020. */
  14021. PointLight.prototype.supportsVSM = function () {
  14022. return false;
  14023. };
  14024. /**
  14025. * Boolean : returns false by default.
  14026. */
  14027. PointLight.prototype.needRefreshPerFrame = function () {
  14028. return false;
  14029. };
  14030. /**
  14031. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14032. */
  14033. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14034. switch (faceIndex) {
  14035. case 0:
  14036. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14037. case 1:
  14038. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14039. case 2:
  14040. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14041. case 3:
  14042. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14043. case 4:
  14044. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14045. case 5:
  14046. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14047. }
  14048. return BABYLON.Vector3.Zero();
  14049. };
  14050. /**
  14051. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14052. * - fov = PI / 2
  14053. * - aspect ratio : 1.0
  14054. * - z-near and far equal to the active camera minZ and maxZ.
  14055. * Returns the PointLight.
  14056. */
  14057. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14058. if (this.customProjectionMatrixBuilder) {
  14059. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14060. }
  14061. else {
  14062. var activeCamera = this.getScene().activeCamera;
  14063. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14064. }
  14065. return this;
  14066. };
  14067. PointLight.prototype._getWorldMatrix = function () {
  14068. if (!this._worldMatrix) {
  14069. this._worldMatrix = BABYLON.Matrix.Identity();
  14070. }
  14071. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14072. return this._worldMatrix;
  14073. };
  14074. /**
  14075. * Returns the integer 0.
  14076. */
  14077. PointLight.prototype.getTypeID = function () {
  14078. return 0;
  14079. };
  14080. return PointLight;
  14081. }(BABYLON.Light));
  14082. __decorate([
  14083. BABYLON.serializeAsVector3()
  14084. ], PointLight.prototype, "position", void 0);
  14085. BABYLON.PointLight = PointLight;
  14086. })(BABYLON || (BABYLON = {}));
  14087. //# sourceMappingURL=babylon.pointLight.js.map
  14088. var BABYLON;
  14089. (function (BABYLON) {
  14090. var SpotLight = (function (_super) {
  14091. __extends(SpotLight, _super);
  14092. /**
  14093. * Creates a SpotLight object in the scene with the passed parameters :
  14094. * - `position` (Vector3) is the initial SpotLight position,
  14095. * - `direction` (Vector3) is the initial SpotLight direction,
  14096. * - `angle` (float, in radians) is the spot light cone angle,
  14097. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14098. * A spot light is a simply light oriented cone.
  14099. * It can cast shadows.
  14100. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14101. */
  14102. function SpotLight(name, position, direction, angle, exponent, scene) {
  14103. var _this = _super.call(this, name, scene) || this;
  14104. _this.position = position;
  14105. _this.direction = direction;
  14106. _this.angle = angle;
  14107. _this.exponent = exponent;
  14108. return _this;
  14109. }
  14110. /**
  14111. * Returns the string "SpotLight".
  14112. */
  14113. SpotLight.prototype.getClassName = function () {
  14114. return "SpotLight";
  14115. };
  14116. /**
  14117. * Returns the SpotLight absolute position in the World (Vector3).
  14118. */
  14119. SpotLight.prototype.getAbsolutePosition = function () {
  14120. return this.transformedPosition ? this.transformedPosition : this.position;
  14121. };
  14122. /**
  14123. * 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.
  14124. * Returns the SpotLight.
  14125. */
  14126. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14127. if (this.customProjectionMatrixBuilder) {
  14128. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14129. }
  14130. else {
  14131. var activeCamera = this.getScene().activeCamera;
  14132. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  14133. }
  14134. return this;
  14135. };
  14136. /**
  14137. * Boolean : false by default.
  14138. */
  14139. SpotLight.prototype.needCube = function () {
  14140. return false;
  14141. };
  14142. /**
  14143. * Boolean : true by default.
  14144. */
  14145. SpotLight.prototype.supportsVSM = function () {
  14146. return true;
  14147. };
  14148. /**
  14149. * Boolean : false by default.
  14150. */
  14151. SpotLight.prototype.needRefreshPerFrame = function () {
  14152. return false;
  14153. };
  14154. /**
  14155. * Returns the SpotLight direction (Vector3) for any passed face index.
  14156. */
  14157. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14158. return this.direction;
  14159. };
  14160. /**
  14161. * Updates the SpotLight direction towards the passed target (Vector3).
  14162. * Returns the updated direction.
  14163. */
  14164. SpotLight.prototype.setDirectionToTarget = function (target) {
  14165. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14166. return this.direction;
  14167. };
  14168. /**
  14169. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14170. */
  14171. SpotLight.prototype.computeTransformedPosition = function () {
  14172. if (this.parent && this.parent.getWorldMatrix) {
  14173. if (!this.transformedPosition) {
  14174. this.transformedPosition = BABYLON.Vector3.Zero();
  14175. }
  14176. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14177. return true;
  14178. }
  14179. return false;
  14180. };
  14181. /**
  14182. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14183. * Return the SpotLight.
  14184. */
  14185. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14186. var normalizeDirection;
  14187. if (this.parent && this.parent.getWorldMatrix) {
  14188. if (!this._transformedDirection) {
  14189. this._transformedDirection = BABYLON.Vector3.Zero();
  14190. }
  14191. this.computeTransformedPosition();
  14192. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14193. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14194. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14195. }
  14196. else {
  14197. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14198. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14199. }
  14200. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14201. return this;
  14202. };
  14203. SpotLight.prototype._getWorldMatrix = function () {
  14204. if (!this._worldMatrix) {
  14205. this._worldMatrix = BABYLON.Matrix.Identity();
  14206. }
  14207. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14208. return this._worldMatrix;
  14209. };
  14210. /**
  14211. * Returns the integer 2.
  14212. */
  14213. SpotLight.prototype.getTypeID = function () {
  14214. return 2;
  14215. };
  14216. /**
  14217. * Returns the SpotLight rotation (Vector3).
  14218. */
  14219. SpotLight.prototype.getRotation = function () {
  14220. this.direction.normalize();
  14221. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14222. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14223. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14224. };
  14225. return SpotLight;
  14226. }(BABYLON.Light));
  14227. __decorate([
  14228. BABYLON.serializeAsVector3()
  14229. ], SpotLight.prototype, "position", void 0);
  14230. __decorate([
  14231. BABYLON.serializeAsVector3()
  14232. ], SpotLight.prototype, "direction", void 0);
  14233. __decorate([
  14234. BABYLON.serialize()
  14235. ], SpotLight.prototype, "angle", void 0);
  14236. __decorate([
  14237. BABYLON.serialize()
  14238. ], SpotLight.prototype, "exponent", void 0);
  14239. BABYLON.SpotLight = SpotLight;
  14240. })(BABYLON || (BABYLON = {}));
  14241. //# sourceMappingURL=babylon.spotLight.js.map
  14242. var BABYLON;
  14243. (function (BABYLON) {
  14244. var HemisphericLight = (function (_super) {
  14245. __extends(HemisphericLight, _super);
  14246. /**
  14247. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14248. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14249. * The HemisphericLight can't cast shadows.
  14250. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14251. */
  14252. function HemisphericLight(name, direction, scene) {
  14253. var _this = _super.call(this, name, scene) || this;
  14254. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14255. _this.direction = direction;
  14256. return _this;
  14257. }
  14258. /**
  14259. * Returns the string "HemisphericLight".
  14260. */
  14261. HemisphericLight.prototype.getClassName = function () {
  14262. return "HemisphericLight";
  14263. };
  14264. /**
  14265. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14266. * Returns the updated direction.
  14267. */
  14268. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14269. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14270. return this.direction;
  14271. };
  14272. HemisphericLight.prototype.getShadowGenerator = function () {
  14273. return null;
  14274. };
  14275. /**
  14276. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14277. * Returns the HemisphericLight.
  14278. */
  14279. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14280. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14281. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14282. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14283. return this;
  14284. };
  14285. HemisphericLight.prototype._getWorldMatrix = function () {
  14286. if (!this._worldMatrix) {
  14287. this._worldMatrix = BABYLON.Matrix.Identity();
  14288. }
  14289. return this._worldMatrix;
  14290. };
  14291. /**
  14292. * Returns the integer 3.
  14293. */
  14294. HemisphericLight.prototype.getTypeID = function () {
  14295. return 3;
  14296. };
  14297. return HemisphericLight;
  14298. }(BABYLON.Light));
  14299. __decorate([
  14300. BABYLON.serializeAsColor3()
  14301. ], HemisphericLight.prototype, "groundColor", void 0);
  14302. __decorate([
  14303. BABYLON.serializeAsVector3()
  14304. ], HemisphericLight.prototype, "direction", void 0);
  14305. BABYLON.HemisphericLight = HemisphericLight;
  14306. })(BABYLON || (BABYLON = {}));
  14307. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14308. /// <reference path="babylon.light.ts" />
  14309. var BABYLON;
  14310. (function (BABYLON) {
  14311. var DirectionalLight = (function (_super) {
  14312. __extends(DirectionalLight, _super);
  14313. /**
  14314. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14315. * The directional light is emitted from everywhere in the given direction.
  14316. * It can cast shawdows.
  14317. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14318. */
  14319. function DirectionalLight(name, direction, scene) {
  14320. var _this = _super.call(this, name, scene) || this;
  14321. _this.shadowOrthoScale = 0.5;
  14322. _this.autoUpdateExtends = true;
  14323. // Cache
  14324. _this._orthoLeft = Number.MAX_VALUE;
  14325. _this._orthoRight = Number.MIN_VALUE;
  14326. _this._orthoTop = Number.MIN_VALUE;
  14327. _this._orthoBottom = Number.MAX_VALUE;
  14328. _this.position = direction.scale(-1.0);
  14329. _this.direction = direction;
  14330. return _this;
  14331. }
  14332. /**
  14333. * Returns the string "DirectionalLight".
  14334. */
  14335. DirectionalLight.prototype.getClassName = function () {
  14336. return "DirectionalLight";
  14337. };
  14338. /**
  14339. * Returns the DirectionalLight absolute position in the World.
  14340. */
  14341. DirectionalLight.prototype.getAbsolutePosition = function () {
  14342. return this.transformedPosition ? this.transformedPosition : this.position;
  14343. };
  14344. /**
  14345. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14346. * Returns the updated DirectionalLight direction (Vector3).
  14347. */
  14348. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14349. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14350. return this.direction;
  14351. };
  14352. /**
  14353. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14354. * Returns the DirectionalLight.
  14355. */
  14356. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14357. if (this.customProjectionMatrixBuilder) {
  14358. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14359. }
  14360. else {
  14361. var activeCamera = this.getScene().activeCamera;
  14362. // Check extends
  14363. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14364. var tempVector3 = BABYLON.Vector3.Zero();
  14365. this._orthoLeft = Number.MAX_VALUE;
  14366. this._orthoRight = Number.MIN_VALUE;
  14367. this._orthoTop = Number.MIN_VALUE;
  14368. this._orthoBottom = Number.MAX_VALUE;
  14369. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14370. var mesh = renderList[meshIndex];
  14371. if (!mesh) {
  14372. continue;
  14373. }
  14374. var boundingInfo = mesh.getBoundingInfo();
  14375. if (!boundingInfo) {
  14376. continue;
  14377. }
  14378. var boundingBox = boundingInfo.boundingBox;
  14379. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14380. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14381. if (tempVector3.x < this._orthoLeft)
  14382. this._orthoLeft = tempVector3.x;
  14383. if (tempVector3.y < this._orthoBottom)
  14384. this._orthoBottom = tempVector3.y;
  14385. if (tempVector3.x > this._orthoRight)
  14386. this._orthoRight = tempVector3.x;
  14387. if (tempVector3.y > this._orthoTop)
  14388. this._orthoTop = tempVector3.y;
  14389. }
  14390. }
  14391. }
  14392. var xOffset = this._orthoRight - this._orthoLeft;
  14393. var yOffset = this._orthoTop - this._orthoBottom;
  14394. 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);
  14395. }
  14396. return this;
  14397. };
  14398. /**
  14399. * Boolean : true by default.
  14400. */
  14401. DirectionalLight.prototype.supportsVSM = function () {
  14402. return true;
  14403. };
  14404. /**
  14405. * Boolean : true by default.
  14406. */
  14407. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14408. return true;
  14409. };
  14410. /**
  14411. * Boolean : false by default.
  14412. */
  14413. DirectionalLight.prototype.needCube = function () {
  14414. return false;
  14415. };
  14416. /**
  14417. * Returns the light direction (Vector3) for any passed face index.
  14418. */
  14419. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14420. return this.direction;
  14421. };
  14422. /**
  14423. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14424. */
  14425. DirectionalLight.prototype.computeTransformedPosition = function () {
  14426. if (this.parent && this.parent.getWorldMatrix) {
  14427. if (!this.transformedPosition) {
  14428. this.transformedPosition = BABYLON.Vector3.Zero();
  14429. }
  14430. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14431. return true;
  14432. }
  14433. return false;
  14434. };
  14435. /**
  14436. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14437. * Returns the DirectionalLight.
  14438. */
  14439. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14440. if (this.parent && this.parent.getWorldMatrix) {
  14441. if (!this._transformedDirection) {
  14442. this._transformedDirection = BABYLON.Vector3.Zero();
  14443. }
  14444. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14445. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14446. return this;
  14447. }
  14448. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14449. return this;
  14450. };
  14451. DirectionalLight.prototype._getWorldMatrix = function () {
  14452. if (!this._worldMatrix) {
  14453. this._worldMatrix = BABYLON.Matrix.Identity();
  14454. }
  14455. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14456. return this._worldMatrix;
  14457. };
  14458. /**
  14459. * Returns the integer 1.
  14460. */
  14461. DirectionalLight.prototype.getTypeID = function () {
  14462. return 1;
  14463. };
  14464. return DirectionalLight;
  14465. }(BABYLON.Light));
  14466. __decorate([
  14467. BABYLON.serializeAsVector3()
  14468. ], DirectionalLight.prototype, "position", void 0);
  14469. __decorate([
  14470. BABYLON.serializeAsVector3()
  14471. ], DirectionalLight.prototype, "direction", void 0);
  14472. __decorate([
  14473. BABYLON.serialize()
  14474. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14475. __decorate([
  14476. BABYLON.serialize()
  14477. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14478. BABYLON.DirectionalLight = DirectionalLight;
  14479. })(BABYLON || (BABYLON = {}));
  14480. //# sourceMappingURL=babylon.directionalLight.js.map
  14481. var BABYLON;
  14482. (function (BABYLON) {
  14483. var ShadowGenerator = (function () {
  14484. /**
  14485. * Creates a ShadowGenerator object.
  14486. * A ShadowGenerator is the required tool to use the shadows.
  14487. * Each light casting shadows needs to use its own ShadowGenerator.
  14488. * Required parameters :
  14489. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14490. * - `light` : the light object generating the shadows.
  14491. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14492. */
  14493. function ShadowGenerator(mapSize, light) {
  14494. var _this = this;
  14495. // Members
  14496. this._filter = ShadowGenerator.FILTER_NONE;
  14497. this.blurScale = 2;
  14498. this._blurBoxOffset = 0;
  14499. this._bias = 0.00005;
  14500. this._lightDirection = BABYLON.Vector3.Zero();
  14501. this.forceBackFacesOnly = false;
  14502. this._darkness = 0;
  14503. this._transparencyShadow = false;
  14504. this._viewMatrix = BABYLON.Matrix.Zero();
  14505. this._projectionMatrix = BABYLON.Matrix.Zero();
  14506. this._transformMatrix = BABYLON.Matrix.Zero();
  14507. this._worldViewProjection = BABYLON.Matrix.Zero();
  14508. this._currentFaceIndex = 0;
  14509. this._currentFaceIndexCache = 0;
  14510. this._useFullFloat = true;
  14511. this._light = light;
  14512. this._scene = light.getScene();
  14513. this._mapSize = mapSize;
  14514. light._shadowGenerator = this;
  14515. // Texture type fallback from float to int if not supported.
  14516. var textureType;
  14517. var caps = this._scene.getEngine().getCaps();
  14518. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14519. this._useFullFloat = true;
  14520. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14521. }
  14522. else {
  14523. this._useFullFloat = false;
  14524. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14525. }
  14526. // Render target
  14527. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14528. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14529. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14530. this._shadowMap.anisotropicFilteringLevel = 1;
  14531. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14532. this._shadowMap.renderParticles = false;
  14533. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14534. _this._currentFaceIndex = faceIndex;
  14535. });
  14536. this._shadowMap.onAfterUnbindObservable.add(function () {
  14537. if (!_this.useBlurVarianceShadowMap) {
  14538. return;
  14539. }
  14540. if (!_this._shadowMap2) {
  14541. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14542. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14543. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14544. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  14545. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  14546. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14547. effect.setTexture("textureSampler", _this._shadowMap);
  14548. });
  14549. _this.blurBoxOffset = 1;
  14550. }
  14551. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14552. });
  14553. // Custom render function
  14554. var renderSubMesh = function (subMesh) {
  14555. var mesh = subMesh.getRenderingMesh();
  14556. var scene = _this._scene;
  14557. var engine = scene.getEngine();
  14558. // Culling
  14559. engine.setState(subMesh.getMaterial().backFaceCulling);
  14560. // Managing instances
  14561. var batch = mesh._getInstancesRenderList(subMesh._id);
  14562. if (batch.mustReturn) {
  14563. return;
  14564. }
  14565. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14566. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14567. engine.enableEffect(_this._effect);
  14568. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14569. var material = subMesh.getMaterial();
  14570. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14571. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14572. if (_this.getLight().needCube()) {
  14573. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14574. }
  14575. // Alpha test
  14576. if (material && material.needAlphaTesting()) {
  14577. var alphaTexture = material.getAlphaTestTexture();
  14578. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14579. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14580. }
  14581. // Bones
  14582. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14583. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14584. }
  14585. if (_this.forceBackFacesOnly) {
  14586. engine.setState(true, 0, false, true);
  14587. }
  14588. // Draw
  14589. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14590. if (_this.forceBackFacesOnly) {
  14591. engine.setState(true, 0, false, false);
  14592. }
  14593. }
  14594. else {
  14595. // Need to reset refresh rate of the shadowMap
  14596. _this._shadowMap.resetRefreshCounter();
  14597. }
  14598. };
  14599. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14600. var index;
  14601. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14602. renderSubMesh(opaqueSubMeshes.data[index]);
  14603. }
  14604. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14605. renderSubMesh(alphaTestSubMeshes.data[index]);
  14606. }
  14607. if (_this._transparencyShadow) {
  14608. for (index = 0; index < transparentSubMeshes.length; index++) {
  14609. renderSubMesh(transparentSubMeshes.data[index]);
  14610. }
  14611. }
  14612. };
  14613. this._shadowMap.onClearObservable.add(function (engine) {
  14614. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  14615. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14616. }
  14617. else {
  14618. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14619. }
  14620. });
  14621. }
  14622. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14623. // Static
  14624. get: function () {
  14625. return ShadowGenerator._FILTER_NONE;
  14626. },
  14627. enumerable: true,
  14628. configurable: true
  14629. });
  14630. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  14631. get: function () {
  14632. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  14633. },
  14634. enumerable: true,
  14635. configurable: true
  14636. });
  14637. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14638. get: function () {
  14639. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14640. },
  14641. enumerable: true,
  14642. configurable: true
  14643. });
  14644. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  14645. get: function () {
  14646. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  14647. },
  14648. enumerable: true,
  14649. configurable: true
  14650. });
  14651. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14652. get: function () {
  14653. return this._bias;
  14654. },
  14655. set: function (bias) {
  14656. this._bias = bias;
  14657. },
  14658. enumerable: true,
  14659. configurable: true
  14660. });
  14661. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14662. get: function () {
  14663. return this._blurBoxOffset;
  14664. },
  14665. set: function (value) {
  14666. var _this = this;
  14667. if (this._blurBoxOffset === value) {
  14668. return;
  14669. }
  14670. this._blurBoxOffset = value;
  14671. if (this._boxBlurPostprocess) {
  14672. this._boxBlurPostprocess.dispose();
  14673. }
  14674. 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);
  14675. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14676. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14677. });
  14678. },
  14679. enumerable: true,
  14680. configurable: true
  14681. });
  14682. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14683. get: function () {
  14684. return this._filter;
  14685. },
  14686. set: function (value) {
  14687. if (this._filter === value) {
  14688. return;
  14689. }
  14690. this._filter = value;
  14691. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  14692. this._shadowMap.anisotropicFilteringLevel = 16;
  14693. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14694. }
  14695. else {
  14696. this._shadowMap.anisotropicFilteringLevel = 1;
  14697. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14698. }
  14699. },
  14700. enumerable: true,
  14701. configurable: true
  14702. });
  14703. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14704. get: function () {
  14705. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  14706. },
  14707. set: function (value) {
  14708. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14709. },
  14710. enumerable: true,
  14711. configurable: true
  14712. });
  14713. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14714. get: function () {
  14715. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  14716. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  14717. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  14718. },
  14719. set: function (value) {
  14720. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14721. },
  14722. enumerable: true,
  14723. configurable: true
  14724. });
  14725. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14726. get: function () {
  14727. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  14728. },
  14729. set: function (value) {
  14730. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  14731. },
  14732. enumerable: true,
  14733. configurable: true
  14734. });
  14735. /**
  14736. * Boolean : true when the ShadowGenerator is finally computed.
  14737. */
  14738. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14739. var defines = [];
  14740. if (this._useFullFloat) {
  14741. defines.push("#define FULLFLOAT");
  14742. }
  14743. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  14744. defines.push("#define VSM");
  14745. }
  14746. if (this.getLight().needCube()) {
  14747. defines.push("#define CUBEMAP");
  14748. }
  14749. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14750. var mesh = subMesh.getMesh();
  14751. var material = subMesh.getMaterial();
  14752. // Alpha test
  14753. if (material && material.needAlphaTesting()) {
  14754. defines.push("#define ALPHATEST");
  14755. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14756. attribs.push(BABYLON.VertexBuffer.UVKind);
  14757. defines.push("#define UV1");
  14758. }
  14759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14760. var alphaTexture = material.getAlphaTestTexture();
  14761. if (alphaTexture.coordinatesIndex === 1) {
  14762. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14763. defines.push("#define UV2");
  14764. }
  14765. }
  14766. }
  14767. // Bones
  14768. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14771. if (mesh.numBoneInfluencers > 4) {
  14772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14774. }
  14775. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14776. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14777. }
  14778. else {
  14779. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14780. }
  14781. // Instances
  14782. if (useInstances) {
  14783. defines.push("#define INSTANCES");
  14784. attribs.push("world0");
  14785. attribs.push("world1");
  14786. attribs.push("world2");
  14787. attribs.push("world3");
  14788. }
  14789. // Get correct effect
  14790. var join = defines.join("\n");
  14791. if (this._cachedDefines !== join) {
  14792. this._cachedDefines = join;
  14793. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  14794. }
  14795. return this._effect.isReady();
  14796. };
  14797. /**
  14798. * Returns a RenderTargetTexture object : the shadow map texture.
  14799. */
  14800. ShadowGenerator.prototype.getShadowMap = function () {
  14801. return this._shadowMap;
  14802. };
  14803. /**
  14804. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14805. */
  14806. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14807. if (this._shadowMap2) {
  14808. return this._shadowMap2;
  14809. }
  14810. return this._shadowMap;
  14811. };
  14812. /**
  14813. * Returns the associated light object.
  14814. */
  14815. ShadowGenerator.prototype.getLight = function () {
  14816. return this._light;
  14817. };
  14818. // Methods
  14819. /**
  14820. * Returns a Matrix object : the updated transformation matrix.
  14821. */
  14822. ShadowGenerator.prototype.getTransformMatrix = function () {
  14823. var scene = this._scene;
  14824. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  14825. return this._transformMatrix;
  14826. }
  14827. this._currentRenderID = scene.getRenderId();
  14828. this._currentFaceIndexCache = this._currentFaceIndex;
  14829. var lightPosition = this._light.position;
  14830. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  14831. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  14832. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  14833. }
  14834. if (this._light.computeTransformedPosition()) {
  14835. lightPosition = this._light.transformedPosition;
  14836. }
  14837. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  14838. this._cachedPosition = lightPosition.clone();
  14839. this._cachedDirection = this._lightDirection.clone();
  14840. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  14841. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  14842. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14843. }
  14844. return this._transformMatrix;
  14845. };
  14846. /**
  14847. * Returns the darkness value (float).
  14848. */
  14849. ShadowGenerator.prototype.getDarkness = function () {
  14850. return this._darkness;
  14851. };
  14852. /**
  14853. * Sets the ShadowGenerator darkness value (float <= 1.0).
  14854. * Returns the ShadowGenerator.
  14855. */
  14856. ShadowGenerator.prototype.setDarkness = function (darkness) {
  14857. if (darkness >= 1.0)
  14858. this._darkness = 1.0;
  14859. else if (darkness <= 0.0)
  14860. this._darkness = 0.0;
  14861. else
  14862. this._darkness = darkness;
  14863. return this;
  14864. };
  14865. /**
  14866. * Sets the ability to have transparent shadow (boolean).
  14867. * Returns the ShadowGenerator.
  14868. */
  14869. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  14870. this._transparencyShadow = hasShadow;
  14871. return this;
  14872. };
  14873. ShadowGenerator.prototype._packHalf = function (depth) {
  14874. var scale = depth * 255.0;
  14875. var fract = scale - Math.floor(scale);
  14876. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  14877. };
  14878. /**
  14879. * Disposes the ShadowGenerator.
  14880. * Returns nothing.
  14881. */
  14882. ShadowGenerator.prototype.dispose = function () {
  14883. this._shadowMap.dispose();
  14884. if (this._shadowMap2) {
  14885. this._shadowMap2.dispose();
  14886. }
  14887. if (this._downSamplePostprocess) {
  14888. this._downSamplePostprocess.dispose();
  14889. }
  14890. if (this._boxBlurPostprocess) {
  14891. this._boxBlurPostprocess.dispose();
  14892. }
  14893. this._light._shadowGenerator = null;
  14894. };
  14895. /**
  14896. * Serializes the ShadowGenerator and returns a serializationObject.
  14897. */
  14898. ShadowGenerator.prototype.serialize = function () {
  14899. var serializationObject = {};
  14900. serializationObject.lightId = this._light.id;
  14901. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  14902. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  14903. serializationObject.usePoissonSampling = this.usePoissonSampling;
  14904. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  14905. serializationObject.darkness = this.getDarkness();
  14906. serializationObject.renderList = [];
  14907. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  14908. var mesh = this.getShadowMap().renderList[meshIndex];
  14909. serializationObject.renderList.push(mesh.id);
  14910. }
  14911. return serializationObject;
  14912. };
  14913. /**
  14914. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  14915. */
  14916. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  14917. //casting to point light, as light is missing the position attr and typescript complains.
  14918. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  14919. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  14920. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  14921. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  14922. meshes.forEach(function (mesh) {
  14923. shadowGenerator.getShadowMap().renderList.push(mesh);
  14924. });
  14925. }
  14926. if (parsedShadowGenerator.usePoissonSampling) {
  14927. shadowGenerator.usePoissonSampling = true;
  14928. }
  14929. else if (parsedShadowGenerator.useVarianceShadowMap) {
  14930. shadowGenerator.useVarianceShadowMap = true;
  14931. }
  14932. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  14933. shadowGenerator.useBlurVarianceShadowMap = true;
  14934. if (parsedShadowGenerator.blurScale) {
  14935. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  14936. }
  14937. if (parsedShadowGenerator.blurBoxOffset) {
  14938. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  14939. }
  14940. }
  14941. if (parsedShadowGenerator.bias !== undefined) {
  14942. shadowGenerator.bias = parsedShadowGenerator.bias;
  14943. }
  14944. if (parsedShadowGenerator.darkness) {
  14945. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  14946. }
  14947. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  14948. return shadowGenerator;
  14949. };
  14950. return ShadowGenerator;
  14951. }());
  14952. ShadowGenerator._FILTER_NONE = 0;
  14953. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  14954. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  14955. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  14956. BABYLON.ShadowGenerator = ShadowGenerator;
  14957. })(BABYLON || (BABYLON = {}));
  14958. //# sourceMappingURL=babylon.shadowGenerator.js.map
  14959. var BABYLON;
  14960. (function (BABYLON) {
  14961. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  14962. if (boxMin.x > sphereCenter.x + sphereRadius)
  14963. return false;
  14964. if (sphereCenter.x - sphereRadius > boxMax.x)
  14965. return false;
  14966. if (boxMin.y > sphereCenter.y + sphereRadius)
  14967. return false;
  14968. if (sphereCenter.y - sphereRadius > boxMax.y)
  14969. return false;
  14970. if (boxMin.z > sphereCenter.z + sphereRadius)
  14971. return false;
  14972. if (sphereCenter.z - sphereRadius > boxMax.z)
  14973. return false;
  14974. return true;
  14975. };
  14976. var getLowestRoot = (function () {
  14977. var result = { root: 0, found: false };
  14978. return function (a, b, c, maxR) {
  14979. result.root = 0;
  14980. result.found = false;
  14981. var determinant = b * b - 4.0 * a * c;
  14982. if (determinant < 0)
  14983. return result;
  14984. var sqrtD = Math.sqrt(determinant);
  14985. var r1 = (-b - sqrtD) / (2.0 * a);
  14986. var r2 = (-b + sqrtD) / (2.0 * a);
  14987. if (r1 > r2) {
  14988. var temp = r2;
  14989. r2 = r1;
  14990. r1 = temp;
  14991. }
  14992. if (r1 > 0 && r1 < maxR) {
  14993. result.root = r1;
  14994. result.found = true;
  14995. return result;
  14996. }
  14997. if (r2 > 0 && r2 < maxR) {
  14998. result.root = r2;
  14999. result.found = true;
  15000. return result;
  15001. }
  15002. return result;
  15003. };
  15004. })();
  15005. var Collider = (function () {
  15006. function Collider() {
  15007. this.radius = new BABYLON.Vector3(1, 1, 1);
  15008. this.retry = 0;
  15009. this.basePointWorld = BABYLON.Vector3.Zero();
  15010. this.velocityWorld = BABYLON.Vector3.Zero();
  15011. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15012. this._collisionPoint = BABYLON.Vector3.Zero();
  15013. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15014. this._tempVector = BABYLON.Vector3.Zero();
  15015. this._tempVector2 = BABYLON.Vector3.Zero();
  15016. this._tempVector3 = BABYLON.Vector3.Zero();
  15017. this._tempVector4 = BABYLON.Vector3.Zero();
  15018. this._edge = BABYLON.Vector3.Zero();
  15019. this._baseToVertex = BABYLON.Vector3.Zero();
  15020. this._destinationPoint = BABYLON.Vector3.Zero();
  15021. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15022. this._displacementVector = BABYLON.Vector3.Zero();
  15023. this._collisionMask = -1;
  15024. }
  15025. Object.defineProperty(Collider.prototype, "collisionMask", {
  15026. get: function () {
  15027. return this._collisionMask;
  15028. },
  15029. set: function (mask) {
  15030. this._collisionMask = !isNaN(mask) ? mask : -1;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. // Methods
  15036. Collider.prototype._initialize = function (source, dir, e) {
  15037. this.velocity = dir;
  15038. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15039. this.basePoint = source;
  15040. source.multiplyToRef(this.radius, this.basePointWorld);
  15041. dir.multiplyToRef(this.radius, this.velocityWorld);
  15042. this.velocityWorldLength = this.velocityWorld.length();
  15043. this.epsilon = e;
  15044. this.collisionFound = false;
  15045. };
  15046. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15047. pa.subtractToRef(point, this._tempVector);
  15048. pb.subtractToRef(point, this._tempVector2);
  15049. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15050. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15051. if (d < 0)
  15052. return false;
  15053. pc.subtractToRef(point, this._tempVector3);
  15054. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15055. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15056. if (d < 0)
  15057. return false;
  15058. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15059. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15060. return d >= 0;
  15061. };
  15062. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15063. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15064. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15065. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15066. return false;
  15067. }
  15068. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15069. return false;
  15070. return true;
  15071. };
  15072. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15073. var t0;
  15074. var embeddedInPlane = false;
  15075. //defensive programming, actually not needed.
  15076. if (!trianglePlaneArray) {
  15077. trianglePlaneArray = [];
  15078. }
  15079. if (!trianglePlaneArray[faceIndex]) {
  15080. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15081. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15082. }
  15083. var trianglePlane = trianglePlaneArray[faceIndex];
  15084. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15085. return;
  15086. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15087. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15088. if (normalDotVelocity == 0) {
  15089. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15090. return;
  15091. embeddedInPlane = true;
  15092. t0 = 0;
  15093. }
  15094. else {
  15095. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15096. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15097. if (t0 > t1) {
  15098. var temp = t1;
  15099. t1 = t0;
  15100. t0 = temp;
  15101. }
  15102. if (t0 > 1.0 || t1 < 0.0)
  15103. return;
  15104. if (t0 < 0)
  15105. t0 = 0;
  15106. if (t0 > 1.0)
  15107. t0 = 1.0;
  15108. }
  15109. this._collisionPoint.copyFromFloats(0, 0, 0);
  15110. var found = false;
  15111. var t = 1.0;
  15112. if (!embeddedInPlane) {
  15113. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15114. this.velocity.scaleToRef(t0, this._tempVector);
  15115. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15116. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15117. found = true;
  15118. t = t0;
  15119. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15120. }
  15121. }
  15122. if (!found) {
  15123. var velocitySquaredLength = this.velocity.lengthSquared();
  15124. var a = velocitySquaredLength;
  15125. this.basePoint.subtractToRef(p1, this._tempVector);
  15126. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15127. var c = this._tempVector.lengthSquared() - 1.0;
  15128. var lowestRoot = getLowestRoot(a, b, c, t);
  15129. if (lowestRoot.found) {
  15130. t = lowestRoot.root;
  15131. found = true;
  15132. this._collisionPoint.copyFrom(p1);
  15133. }
  15134. this.basePoint.subtractToRef(p2, this._tempVector);
  15135. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15136. c = this._tempVector.lengthSquared() - 1.0;
  15137. lowestRoot = getLowestRoot(a, b, c, t);
  15138. if (lowestRoot.found) {
  15139. t = lowestRoot.root;
  15140. found = true;
  15141. this._collisionPoint.copyFrom(p2);
  15142. }
  15143. this.basePoint.subtractToRef(p3, this._tempVector);
  15144. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15145. c = this._tempVector.lengthSquared() - 1.0;
  15146. lowestRoot = getLowestRoot(a, b, c, t);
  15147. if (lowestRoot.found) {
  15148. t = lowestRoot.root;
  15149. found = true;
  15150. this._collisionPoint.copyFrom(p3);
  15151. }
  15152. p2.subtractToRef(p1, this._edge);
  15153. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15154. var edgeSquaredLength = this._edge.lengthSquared();
  15155. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15156. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15157. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15158. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15159. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15160. lowestRoot = getLowestRoot(a, b, c, t);
  15161. if (lowestRoot.found) {
  15162. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15163. if (f >= 0.0 && f <= 1.0) {
  15164. t = lowestRoot.root;
  15165. found = true;
  15166. this._edge.scaleInPlace(f);
  15167. p1.addToRef(this._edge, this._collisionPoint);
  15168. }
  15169. }
  15170. p3.subtractToRef(p2, this._edge);
  15171. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15172. edgeSquaredLength = this._edge.lengthSquared();
  15173. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15174. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15175. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15176. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15177. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15178. lowestRoot = getLowestRoot(a, b, c, t);
  15179. if (lowestRoot.found) {
  15180. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15181. if (f >= 0.0 && f <= 1.0) {
  15182. t = lowestRoot.root;
  15183. found = true;
  15184. this._edge.scaleInPlace(f);
  15185. p2.addToRef(this._edge, this._collisionPoint);
  15186. }
  15187. }
  15188. p1.subtractToRef(p3, this._edge);
  15189. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15190. edgeSquaredLength = this._edge.lengthSquared();
  15191. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15192. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15193. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15194. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15195. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15196. lowestRoot = getLowestRoot(a, b, c, t);
  15197. if (lowestRoot.found) {
  15198. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15199. if (f >= 0.0 && f <= 1.0) {
  15200. t = lowestRoot.root;
  15201. found = true;
  15202. this._edge.scaleInPlace(f);
  15203. p3.addToRef(this._edge, this._collisionPoint);
  15204. }
  15205. }
  15206. }
  15207. if (found) {
  15208. var distToCollision = t * this.velocity.length();
  15209. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15210. if (!this.intersectionPoint) {
  15211. this.intersectionPoint = this._collisionPoint.clone();
  15212. }
  15213. else {
  15214. this.intersectionPoint.copyFrom(this._collisionPoint);
  15215. }
  15216. this.nearestDistance = distToCollision;
  15217. this.collisionFound = true;
  15218. }
  15219. }
  15220. };
  15221. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15222. for (var i = indexStart; i < indexEnd; i += 3) {
  15223. var p1 = pts[indices[i] - decal];
  15224. var p2 = pts[indices[i + 1] - decal];
  15225. var p3 = pts[indices[i + 2] - decal];
  15226. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15227. }
  15228. };
  15229. Collider.prototype._getResponse = function (pos, vel) {
  15230. pos.addToRef(vel, this._destinationPoint);
  15231. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15232. this.basePoint.addToRef(vel, pos);
  15233. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15234. this._slidePlaneNormal.normalize();
  15235. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15236. pos.addInPlace(this._displacementVector);
  15237. this.intersectionPoint.addInPlace(this._displacementVector);
  15238. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15239. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15240. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15241. };
  15242. return Collider;
  15243. }());
  15244. BABYLON.Collider = Collider;
  15245. })(BABYLON || (BABYLON = {}));
  15246. //# sourceMappingURL=babylon.collider.js.map
  15247. var BABYLON;
  15248. (function (BABYLON) {
  15249. //WebWorker code will be inserted to this variable.
  15250. BABYLON.CollisionWorker = "";
  15251. var WorkerTaskType;
  15252. (function (WorkerTaskType) {
  15253. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15254. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15255. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15256. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15257. var WorkerReplyType;
  15258. (function (WorkerReplyType) {
  15259. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15260. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15261. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15262. var CollisionCoordinatorWorker = (function () {
  15263. function CollisionCoordinatorWorker() {
  15264. var _this = this;
  15265. this._scaledPosition = BABYLON.Vector3.Zero();
  15266. this._scaledVelocity = BABYLON.Vector3.Zero();
  15267. this.onMeshUpdated = function (mesh) {
  15268. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15269. };
  15270. this.onGeometryUpdated = function (geometry) {
  15271. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15272. };
  15273. this._afterRender = function () {
  15274. if (!_this._init)
  15275. return;
  15276. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15277. return;
  15278. }
  15279. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15280. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15281. if (_this._runningUpdated > 4) {
  15282. return;
  15283. }
  15284. ++_this._runningUpdated;
  15285. var payload = {
  15286. updatedMeshes: _this._addUpdateMeshesList,
  15287. updatedGeometries: _this._addUpdateGeometriesList,
  15288. removedGeometries: _this._toRemoveGeometryArray,
  15289. removedMeshes: _this._toRemoveMeshesArray
  15290. };
  15291. var message = {
  15292. payload: payload,
  15293. taskType: WorkerTaskType.UPDATE
  15294. };
  15295. var serializable = [];
  15296. for (var id in payload.updatedGeometries) {
  15297. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15298. //prepare transferables
  15299. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15300. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15301. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15302. }
  15303. }
  15304. _this._worker.postMessage(message, serializable);
  15305. _this._addUpdateMeshesList = {};
  15306. _this._addUpdateGeometriesList = {};
  15307. _this._toRemoveGeometryArray = [];
  15308. _this._toRemoveMeshesArray = [];
  15309. };
  15310. this._onMessageFromWorker = function (e) {
  15311. var returnData = e.data;
  15312. if (returnData.error != WorkerReplyType.SUCCESS) {
  15313. //TODO what errors can be returned from the worker?
  15314. BABYLON.Tools.Warn("error returned from worker!");
  15315. return;
  15316. }
  15317. switch (returnData.taskType) {
  15318. case WorkerTaskType.INIT:
  15319. _this._init = true;
  15320. //Update the worked with ALL of the scene's current state
  15321. _this._scene.meshes.forEach(function (mesh) {
  15322. _this.onMeshAdded(mesh);
  15323. });
  15324. _this._scene.getGeometries().forEach(function (geometry) {
  15325. _this.onGeometryAdded(geometry);
  15326. });
  15327. break;
  15328. case WorkerTaskType.UPDATE:
  15329. _this._runningUpdated--;
  15330. break;
  15331. case WorkerTaskType.COLLIDE:
  15332. _this._runningCollisionTask = false;
  15333. var returnPayload = returnData.payload;
  15334. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15335. return;
  15336. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15337. //cleanup
  15338. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15339. break;
  15340. }
  15341. };
  15342. this._collisionsCallbackArray = [];
  15343. this._init = false;
  15344. this._runningUpdated = 0;
  15345. this._runningCollisionTask = false;
  15346. this._addUpdateMeshesList = {};
  15347. this._addUpdateGeometriesList = {};
  15348. this._toRemoveGeometryArray = [];
  15349. this._toRemoveMeshesArray = [];
  15350. }
  15351. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15352. if (!this._init)
  15353. return;
  15354. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15355. return;
  15356. position.divideToRef(collider.radius, this._scaledPosition);
  15357. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15358. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15359. var payload = {
  15360. collider: {
  15361. position: this._scaledPosition.asArray(),
  15362. velocity: this._scaledVelocity.asArray(),
  15363. radius: collider.radius.asArray()
  15364. },
  15365. collisionId: collisionIndex,
  15366. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15367. maximumRetry: maximumRetry
  15368. };
  15369. var message = {
  15370. payload: payload,
  15371. taskType: WorkerTaskType.COLLIDE
  15372. };
  15373. this._worker.postMessage(message);
  15374. };
  15375. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15376. this._scene = scene;
  15377. this._scene.registerAfterRender(this._afterRender);
  15378. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15379. this._worker = new Worker(workerUrl);
  15380. this._worker.onmessage = this._onMessageFromWorker;
  15381. var message = {
  15382. payload: {},
  15383. taskType: WorkerTaskType.INIT
  15384. };
  15385. this._worker.postMessage(message);
  15386. };
  15387. CollisionCoordinatorWorker.prototype.destroy = function () {
  15388. this._scene.unregisterAfterRender(this._afterRender);
  15389. this._worker.terminate();
  15390. };
  15391. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15392. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15393. this.onMeshUpdated(mesh);
  15394. };
  15395. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15396. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15397. };
  15398. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15399. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15400. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15401. this.onGeometryUpdated(geometry);
  15402. };
  15403. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15404. this._toRemoveGeometryArray.push(geometry.id);
  15405. };
  15406. return CollisionCoordinatorWorker;
  15407. }());
  15408. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15409. var submeshes = [];
  15410. if (mesh.subMeshes) {
  15411. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15412. return {
  15413. position: idx,
  15414. verticesStart: sm.verticesStart,
  15415. verticesCount: sm.verticesCount,
  15416. indexStart: sm.indexStart,
  15417. indexCount: sm.indexCount,
  15418. hasMaterial: !!sm.getMaterial(),
  15419. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15420. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15421. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15422. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15423. };
  15424. });
  15425. }
  15426. var geometryId = null;
  15427. if (mesh instanceof BABYLON.Mesh) {
  15428. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15429. }
  15430. else if (mesh instanceof BABYLON.InstancedMesh) {
  15431. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15432. }
  15433. return {
  15434. uniqueId: mesh.uniqueId,
  15435. id: mesh.id,
  15436. name: mesh.name,
  15437. geometryId: geometryId,
  15438. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15439. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15440. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15441. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15442. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15443. subMeshes: submeshes,
  15444. checkCollisions: mesh.checkCollisions
  15445. };
  15446. };
  15447. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15448. return {
  15449. id: geometry.id,
  15450. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15451. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15452. indices: new Uint32Array(geometry.getIndices() || []),
  15453. };
  15454. };
  15455. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15456. var CollisionCoordinatorLegacy = (function () {
  15457. function CollisionCoordinatorLegacy() {
  15458. this._scaledPosition = BABYLON.Vector3.Zero();
  15459. this._scaledVelocity = BABYLON.Vector3.Zero();
  15460. this._finalPosition = BABYLON.Vector3.Zero();
  15461. }
  15462. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15463. position.divideToRef(collider.radius, this._scaledPosition);
  15464. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15465. collider.collidedMesh = null;
  15466. collider.retry = 0;
  15467. collider.initialVelocity = this._scaledVelocity;
  15468. collider.initialPosition = this._scaledPosition;
  15469. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15470. this._finalPosition.multiplyInPlace(collider.radius);
  15471. //run the callback
  15472. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15473. };
  15474. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15475. this._scene = scene;
  15476. };
  15477. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15478. //Legacy need no destruction method.
  15479. };
  15480. //No update in legacy mode
  15481. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15482. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15483. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15484. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15485. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15486. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15487. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15488. if (excludedMesh === void 0) { excludedMesh = null; }
  15489. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15490. if (collider.retry >= maximumRetry) {
  15491. finalPosition.copyFrom(position);
  15492. return;
  15493. }
  15494. // Check if this is a mesh else camera or -1
  15495. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15496. collider._initialize(position, velocity, closeDistance);
  15497. // Check all meshes
  15498. for (var index = 0; index < this._scene.meshes.length; index++) {
  15499. var mesh = this._scene.meshes[index];
  15500. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15501. mesh._checkCollision(collider);
  15502. }
  15503. }
  15504. if (!collider.collisionFound) {
  15505. position.addToRef(velocity, finalPosition);
  15506. return;
  15507. }
  15508. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15509. collider._getResponse(position, velocity);
  15510. }
  15511. if (velocity.length() <= closeDistance) {
  15512. finalPosition.copyFrom(position);
  15513. return;
  15514. }
  15515. collider.retry++;
  15516. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15517. };
  15518. return CollisionCoordinatorLegacy;
  15519. }());
  15520. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15521. })(BABYLON || (BABYLON = {}));
  15522. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15523. var BABYLON;
  15524. (function (BABYLON) {
  15525. var Camera = (function (_super) {
  15526. __extends(Camera, _super);
  15527. function Camera(name, position, scene) {
  15528. var _this = _super.call(this, name, scene) || this;
  15529. _this.upVector = BABYLON.Vector3.Up();
  15530. _this.orthoLeft = null;
  15531. _this.orthoRight = null;
  15532. _this.orthoBottom = null;
  15533. _this.orthoTop = null;
  15534. _this.fov = 0.8;
  15535. _this.minZ = 1.0;
  15536. _this.maxZ = 10000.0;
  15537. _this.inertia = 0.9;
  15538. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15539. _this.isIntermediate = false;
  15540. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15541. _this.layerMask = 0x0FFFFFFF;
  15542. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15543. // Camera rig members
  15544. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15545. _this._rigCameras = new Array();
  15546. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15547. // Cache
  15548. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15549. _this._projectionMatrix = new BABYLON.Matrix();
  15550. _this._doNotComputeProjectionMatrix = false;
  15551. _this._postProcesses = new Array();
  15552. _this._transformMatrix = BABYLON.Matrix.Zero();
  15553. _this._activeMeshes = new BABYLON.SmartArray(256);
  15554. _this._globalPosition = BABYLON.Vector3.Zero();
  15555. _this._refreshFrustumPlanes = true;
  15556. _this.getScene().addCamera(_this);
  15557. if (!_this.getScene().activeCamera) {
  15558. _this.getScene().activeCamera = _this;
  15559. }
  15560. _this.position = position;
  15561. return _this;
  15562. }
  15563. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15564. get: function () {
  15565. return Camera._PERSPECTIVE_CAMERA;
  15566. },
  15567. enumerable: true,
  15568. configurable: true
  15569. });
  15570. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15571. get: function () {
  15572. return Camera._ORTHOGRAPHIC_CAMERA;
  15573. },
  15574. enumerable: true,
  15575. configurable: true
  15576. });
  15577. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15578. get: function () {
  15579. return Camera._FOVMODE_VERTICAL_FIXED;
  15580. },
  15581. enumerable: true,
  15582. configurable: true
  15583. });
  15584. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15585. get: function () {
  15586. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15587. },
  15588. enumerable: true,
  15589. configurable: true
  15590. });
  15591. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15592. get: function () {
  15593. return Camera._RIG_MODE_NONE;
  15594. },
  15595. enumerable: true,
  15596. configurable: true
  15597. });
  15598. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15599. get: function () {
  15600. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15601. },
  15602. enumerable: true,
  15603. configurable: true
  15604. });
  15605. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15606. get: function () {
  15607. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15608. },
  15609. enumerable: true,
  15610. configurable: true
  15611. });
  15612. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15613. get: function () {
  15614. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15615. },
  15616. enumerable: true,
  15617. configurable: true
  15618. });
  15619. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15620. get: function () {
  15621. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15622. },
  15623. enumerable: true,
  15624. configurable: true
  15625. });
  15626. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15627. get: function () {
  15628. return Camera._RIG_MODE_VR;
  15629. },
  15630. enumerable: true,
  15631. configurable: true
  15632. });
  15633. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15634. get: function () {
  15635. return Camera._RIG_MODE_WEBVR;
  15636. },
  15637. enumerable: true,
  15638. configurable: true
  15639. });
  15640. Camera.prototype.getClassName = function () {
  15641. return "Camera";
  15642. };
  15643. /**
  15644. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15645. */
  15646. Camera.prototype.toString = function (fullDetails) {
  15647. var ret = "Name: " + this.name;
  15648. ret += ", type: " + this.getClassName();
  15649. if (this.animations) {
  15650. for (var i = 0; i < this.animations.length; i++) {
  15651. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15652. }
  15653. }
  15654. if (fullDetails) {
  15655. }
  15656. return ret;
  15657. };
  15658. Object.defineProperty(Camera.prototype, "globalPosition", {
  15659. get: function () {
  15660. return this._globalPosition;
  15661. },
  15662. enumerable: true,
  15663. configurable: true
  15664. });
  15665. Camera.prototype.getActiveMeshes = function () {
  15666. return this._activeMeshes;
  15667. };
  15668. Camera.prototype.isActiveMesh = function (mesh) {
  15669. return (this._activeMeshes.indexOf(mesh) !== -1);
  15670. };
  15671. //Cache
  15672. Camera.prototype._initCache = function () {
  15673. _super.prototype._initCache.call(this);
  15674. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15675. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15676. this._cache.mode = undefined;
  15677. this._cache.minZ = undefined;
  15678. this._cache.maxZ = undefined;
  15679. this._cache.fov = undefined;
  15680. this._cache.fovMode = undefined;
  15681. this._cache.aspectRatio = undefined;
  15682. this._cache.orthoLeft = undefined;
  15683. this._cache.orthoRight = undefined;
  15684. this._cache.orthoBottom = undefined;
  15685. this._cache.orthoTop = undefined;
  15686. this._cache.renderWidth = undefined;
  15687. this._cache.renderHeight = undefined;
  15688. };
  15689. Camera.prototype._updateCache = function (ignoreParentClass) {
  15690. if (!ignoreParentClass) {
  15691. _super.prototype._updateCache.call(this);
  15692. }
  15693. var engine = this.getEngine();
  15694. this._cache.position.copyFrom(this.position);
  15695. this._cache.upVector.copyFrom(this.upVector);
  15696. this._cache.mode = this.mode;
  15697. this._cache.minZ = this.minZ;
  15698. this._cache.maxZ = this.maxZ;
  15699. this._cache.fov = this.fov;
  15700. this._cache.fovMode = this.fovMode;
  15701. this._cache.aspectRatio = engine.getAspectRatio(this);
  15702. this._cache.orthoLeft = this.orthoLeft;
  15703. this._cache.orthoRight = this.orthoRight;
  15704. this._cache.orthoBottom = this.orthoBottom;
  15705. this._cache.orthoTop = this.orthoTop;
  15706. this._cache.renderWidth = engine.getRenderWidth();
  15707. this._cache.renderHeight = engine.getRenderHeight();
  15708. };
  15709. Camera.prototype._updateFromScene = function () {
  15710. this.updateCache();
  15711. this.update();
  15712. };
  15713. // Synchronized
  15714. Camera.prototype._isSynchronized = function () {
  15715. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15716. };
  15717. Camera.prototype._isSynchronizedViewMatrix = function () {
  15718. if (!_super.prototype._isSynchronized.call(this))
  15719. return false;
  15720. return this._cache.position.equals(this.position)
  15721. && this._cache.upVector.equals(this.upVector)
  15722. && this.isSynchronizedWithParent();
  15723. };
  15724. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15725. var check = this._cache.mode === this.mode
  15726. && this._cache.minZ === this.minZ
  15727. && this._cache.maxZ === this.maxZ;
  15728. if (!check) {
  15729. return false;
  15730. }
  15731. var engine = this.getEngine();
  15732. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15733. check = this._cache.fov === this.fov
  15734. && this._cache.fovMode === this.fovMode
  15735. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15736. }
  15737. else {
  15738. check = this._cache.orthoLeft === this.orthoLeft
  15739. && this._cache.orthoRight === this.orthoRight
  15740. && this._cache.orthoBottom === this.orthoBottom
  15741. && this._cache.orthoTop === this.orthoTop
  15742. && this._cache.renderWidth === engine.getRenderWidth()
  15743. && this._cache.renderHeight === engine.getRenderHeight();
  15744. }
  15745. return check;
  15746. };
  15747. // Controls
  15748. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15749. };
  15750. Camera.prototype.detachControl = function (element) {
  15751. };
  15752. Camera.prototype.update = function () {
  15753. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15754. this._updateRigCameras();
  15755. }
  15756. this._checkInputs();
  15757. };
  15758. Camera.prototype._checkInputs = function () {
  15759. };
  15760. Object.defineProperty(Camera.prototype, "rigCameras", {
  15761. get: function () {
  15762. return this._rigCameras;
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15768. get: function () {
  15769. return this._rigPostProcess;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15775. // invalidate framebuffer
  15776. if (this._postProcesses.length > 0) {
  15777. this._postProcesses[0].markTextureDirty();
  15778. }
  15779. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15780. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15781. var cam = this._rigCameras[i];
  15782. var rigPostProcess = cam._rigPostProcess;
  15783. // for VR rig, there does not have to be a post process
  15784. if (rigPostProcess) {
  15785. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15786. if (isPass) {
  15787. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15788. cam.isIntermediate = this._postProcesses.length === 0;
  15789. }
  15790. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15791. rigPostProcess.markTextureDirty();
  15792. }
  15793. else {
  15794. cam._postProcesses = this._postProcesses.slice(0);
  15795. }
  15796. }
  15797. };
  15798. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15799. if (insertAt === void 0) { insertAt = null; }
  15800. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15801. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15802. return 0;
  15803. }
  15804. if (insertAt == null || insertAt < 0) {
  15805. this._postProcesses.push(postProcess);
  15806. }
  15807. else {
  15808. this._postProcesses.splice(insertAt, 0, postProcess);
  15809. }
  15810. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15811. return this._postProcesses.indexOf(postProcess);
  15812. };
  15813. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15814. if (atIndices === void 0) { atIndices = null; }
  15815. var result = [];
  15816. var i;
  15817. var index;
  15818. if (!atIndices) {
  15819. var idx = this._postProcesses.indexOf(postProcess);
  15820. if (idx !== -1) {
  15821. this._postProcesses.splice(idx, 1);
  15822. }
  15823. }
  15824. else {
  15825. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15826. // iterate descending, so can just splice as we go
  15827. for (i = atIndices.length - 1; i >= 0; i--) {
  15828. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15829. result.push(i);
  15830. continue;
  15831. }
  15832. index = atIndices[i];
  15833. this._postProcesses.splice(index, 1);
  15834. }
  15835. }
  15836. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15837. return result;
  15838. };
  15839. Camera.prototype.getWorldMatrix = function () {
  15840. if (!this._worldMatrix) {
  15841. this._worldMatrix = BABYLON.Matrix.Identity();
  15842. }
  15843. var viewMatrix = this.getViewMatrix();
  15844. viewMatrix.invertToRef(this._worldMatrix);
  15845. return this._worldMatrix;
  15846. };
  15847. Camera.prototype._getViewMatrix = function () {
  15848. return BABYLON.Matrix.Identity();
  15849. };
  15850. Camera.prototype.getViewMatrix = function (force) {
  15851. this._computedViewMatrix = this._computeViewMatrix(force);
  15852. if (!force && this._isSynchronizedViewMatrix()) {
  15853. return this._computedViewMatrix;
  15854. }
  15855. this._refreshFrustumPlanes = true;
  15856. if (!this.parent || !this.parent.getWorldMatrix) {
  15857. this._globalPosition.copyFrom(this.position);
  15858. }
  15859. else {
  15860. if (!this._worldMatrix) {
  15861. this._worldMatrix = BABYLON.Matrix.Identity();
  15862. }
  15863. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15864. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15865. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15866. this._computedViewMatrix.invert();
  15867. this._markSyncedWithParent();
  15868. }
  15869. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15870. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15871. }
  15872. this._currentRenderId = this.getScene().getRenderId();
  15873. return this._computedViewMatrix;
  15874. };
  15875. Camera.prototype._computeViewMatrix = function (force) {
  15876. if (!force && this._isSynchronizedViewMatrix()) {
  15877. return this._computedViewMatrix;
  15878. }
  15879. this._computedViewMatrix = this._getViewMatrix();
  15880. this._currentRenderId = this.getScene().getRenderId();
  15881. return this._computedViewMatrix;
  15882. };
  15883. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15884. this._doNotComputeProjectionMatrix = true;
  15885. if (projection !== undefined) {
  15886. this._projectionMatrix = projection;
  15887. }
  15888. };
  15889. ;
  15890. Camera.prototype.unfreezeProjectionMatrix = function () {
  15891. this._doNotComputeProjectionMatrix = false;
  15892. };
  15893. ;
  15894. Camera.prototype.getProjectionMatrix = function (force) {
  15895. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15896. return this._projectionMatrix;
  15897. }
  15898. this._refreshFrustumPlanes = true;
  15899. var engine = this.getEngine();
  15900. var scene = this.getScene();
  15901. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15902. if (this.minZ <= 0) {
  15903. this.minZ = 0.1;
  15904. }
  15905. if (scene.useRightHandedSystem) {
  15906. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15907. }
  15908. else {
  15909. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15910. }
  15911. return this._projectionMatrix;
  15912. }
  15913. var halfWidth = engine.getRenderWidth() / 2.0;
  15914. var halfHeight = engine.getRenderHeight() / 2.0;
  15915. if (scene.useRightHandedSystem) {
  15916. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15917. }
  15918. else {
  15919. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15920. }
  15921. return this._projectionMatrix;
  15922. };
  15923. Camera.prototype.getTranformationMatrix = function () {
  15924. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15925. return this._transformMatrix;
  15926. };
  15927. Camera.prototype.updateFrustumPlanes = function () {
  15928. if (!this._refreshFrustumPlanes) {
  15929. return;
  15930. }
  15931. this.getTranformationMatrix();
  15932. if (!this._frustumPlanes) {
  15933. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15934. }
  15935. else {
  15936. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15937. }
  15938. this._refreshFrustumPlanes = false;
  15939. };
  15940. Camera.prototype.isInFrustum = function (target) {
  15941. this.updateFrustumPlanes();
  15942. return target.isInFrustum(this._frustumPlanes);
  15943. };
  15944. Camera.prototype.isCompletelyInFrustum = function (target) {
  15945. this.updateFrustumPlanes();
  15946. return target.isCompletelyInFrustum(this._frustumPlanes);
  15947. };
  15948. Camera.prototype.dispose = function () {
  15949. // Animations
  15950. this.getScene().stopAnimation(this);
  15951. // Remove from scene
  15952. this.getScene().removeCamera(this);
  15953. while (this._rigCameras.length > 0) {
  15954. this._rigCameras.pop().dispose();
  15955. }
  15956. // Postprocesses
  15957. var i = this._postProcesses.length;
  15958. while (--i >= 0) {
  15959. this._postProcesses[i].dispose(this);
  15960. }
  15961. _super.prototype.dispose.call(this);
  15962. };
  15963. // ---- Camera rigs section ----
  15964. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15965. while (this._rigCameras.length > 0) {
  15966. this._rigCameras.pop().dispose();
  15967. }
  15968. this.cameraRigMode = mode;
  15969. this._cameraRigParams = {};
  15970. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15971. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15972. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15973. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15974. // create the rig cameras, unless none
  15975. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15976. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15977. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15978. }
  15979. switch (this.cameraRigMode) {
  15980. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15981. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15982. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15983. break;
  15984. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15985. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15986. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15987. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15988. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15989. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15990. break;
  15991. case Camera.RIG_MODE_VR:
  15992. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15993. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15994. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15995. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15996. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15997. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15998. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15999. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16000. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16001. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16002. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16003. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16004. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16005. if (metrics.compensateDistortion) {
  16006. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16007. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16008. }
  16009. break;
  16010. case Camera.RIG_MODE_WEBVR:
  16011. if (rigParams.vrDisplay) {
  16012. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16013. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16014. //Left eye
  16015. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16016. this._rigCameras[0].setCameraRigParameter("left", true);
  16017. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16018. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16019. //this._rigCameras[0].setCameraRigParameter('eyeParameters', leftEye);
  16020. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16021. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16022. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16023. this._rigCameras[0]._isSynchronizedViewMatrix = this._isSynchronizedViewMatrix;
  16024. //Right eye
  16025. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16026. //this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16027. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16028. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16029. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16030. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16031. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16032. this._rigCameras[1]._isSynchronizedViewMatrix = this._isSynchronizedViewMatrix;
  16033. }
  16034. break;
  16035. }
  16036. this._cascadePostProcessesToRigCams();
  16037. this.
  16038. update();
  16039. };
  16040. Camera.prototype._getVRProjectionMatrix = function () {
  16041. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16042. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16043. return this._projectionMatrix;
  16044. };
  16045. /**
  16046. * This function MUST be overwritten by the different WebVR cameras available.
  16047. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16048. */
  16049. Camera.prototype._getWebVRProjectionMatrix = function () {
  16050. return BABYLON.Matrix.Identity();
  16051. };
  16052. /**
  16053. * This function MUST be overwritten by the different WebVR cameras available.
  16054. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16055. */
  16056. Camera.prototype._getWebVRViewMatrix = function () {
  16057. return BABYLON.Matrix.Identity();
  16058. };
  16059. Camera.prototype.setCameraRigParameter = function (name, value) {
  16060. if (!this._cameraRigParams) {
  16061. this._cameraRigParams = {};
  16062. }
  16063. this._cameraRigParams[name] = value;
  16064. //provisionnally:
  16065. if (name === "interaxialDistance") {
  16066. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16067. }
  16068. };
  16069. /**
  16070. * needs to be overridden by children so sub has required properties to be copied
  16071. */
  16072. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16073. return null;
  16074. };
  16075. /**
  16076. * May need to be overridden by children
  16077. */
  16078. Camera.prototype._updateRigCameras = function () {
  16079. for (var i = 0; i < this._rigCameras.length; i++) {
  16080. this._rigCameras[i].minZ = this.minZ;
  16081. this._rigCameras[i].maxZ = this.maxZ;
  16082. this._rigCameras[i].fov = this.fov;
  16083. }
  16084. // only update viewport when ANAGLYPH
  16085. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16086. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16087. }
  16088. };
  16089. Camera.prototype._setupInputs = function () {
  16090. };
  16091. Camera.prototype.serialize = function () {
  16092. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16093. // Type
  16094. serializationObject.type = this.getClassName();
  16095. // Parent
  16096. if (this.parent) {
  16097. serializationObject.parentId = this.parent.id;
  16098. }
  16099. if (this.inputs) {
  16100. this.inputs.serialize(serializationObject);
  16101. }
  16102. // Animations
  16103. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16104. serializationObject.ranges = this.serializeAnimationRanges();
  16105. return serializationObject;
  16106. };
  16107. Camera.prototype.clone = function (name) {
  16108. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16109. };
  16110. Camera.prototype.getDirection = function (localAxis) {
  16111. var result = BABYLON.Vector3.Zero();
  16112. this.getDirectionToRef(localAxis, result);
  16113. return result;
  16114. };
  16115. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16116. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16117. };
  16118. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16119. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16120. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16121. switch (type) {
  16122. case "ArcRotateCamera":
  16123. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16124. case "DeviceOrientationCamera":
  16125. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16126. case "FollowCamera":
  16127. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16128. case "ArcFollowCamera":
  16129. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16130. case "GamepadCamera":
  16131. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16132. case "TouchCamera":
  16133. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16134. case "VirtualJoysticksCamera":
  16135. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16136. case "WebVRFreeCamera":
  16137. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16138. case "WebVRGamepadCamera":
  16139. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16140. case "VRDeviceOrientationFreeCamera":
  16141. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16142. case "VRDeviceOrientationGamepadCamera":
  16143. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16144. case "AnaglyphArcRotateCamera":
  16145. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16146. case "AnaglyphFreeCamera":
  16147. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16148. case "AnaglyphGamepadCamera":
  16149. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16150. case "AnaglyphUniversalCamera":
  16151. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16152. case "StereoscopicArcRotateCamera":
  16153. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16154. case "StereoscopicFreeCamera":
  16155. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16156. case "StereoscopicGamepadCamera":
  16157. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16158. case "StereoscopicUniversalCamera":
  16159. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16160. case "FreeCamera":
  16161. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16162. default:
  16163. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16164. }
  16165. };
  16166. Camera.Parse = function (parsedCamera, scene) {
  16167. var type = parsedCamera.type;
  16168. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16169. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16170. // Parent
  16171. if (parsedCamera.parentId) {
  16172. camera._waitingParentId = parsedCamera.parentId;
  16173. }
  16174. //If camera has an input manager, let it parse inputs settings
  16175. if (camera.inputs) {
  16176. camera.inputs.parse(parsedCamera);
  16177. camera._setupInputs();
  16178. }
  16179. // Target
  16180. if (parsedCamera.target) {
  16181. if (camera.setTarget) {
  16182. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16183. }
  16184. }
  16185. // Apply 3d rig, when found
  16186. if (parsedCamera.cameraRigMode) {
  16187. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16188. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16189. }
  16190. // Animations
  16191. if (parsedCamera.animations) {
  16192. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16193. var parsedAnimation = parsedCamera.animations[animationIndex];
  16194. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16195. }
  16196. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16197. }
  16198. if (parsedCamera.autoAnimate) {
  16199. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16200. }
  16201. return camera;
  16202. };
  16203. return Camera;
  16204. }(BABYLON.Node));
  16205. // Statics
  16206. Camera._PERSPECTIVE_CAMERA = 0;
  16207. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16208. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16209. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16210. Camera._RIG_MODE_NONE = 0;
  16211. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16212. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16213. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16214. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16215. Camera._RIG_MODE_VR = 20;
  16216. Camera._RIG_MODE_WEBVR = 21;
  16217. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16218. __decorate([
  16219. BABYLON.serializeAsVector3()
  16220. ], Camera.prototype, "position", void 0);
  16221. __decorate([
  16222. BABYLON.serializeAsVector3()
  16223. ], Camera.prototype, "upVector", void 0);
  16224. __decorate([
  16225. BABYLON.serialize()
  16226. ], Camera.prototype, "orthoLeft", void 0);
  16227. __decorate([
  16228. BABYLON.serialize()
  16229. ], Camera.prototype, "orthoRight", void 0);
  16230. __decorate([
  16231. BABYLON.serialize()
  16232. ], Camera.prototype, "orthoBottom", void 0);
  16233. __decorate([
  16234. BABYLON.serialize()
  16235. ], Camera.prototype, "orthoTop", void 0);
  16236. __decorate([
  16237. BABYLON.serialize()
  16238. ], Camera.prototype, "fov", void 0);
  16239. __decorate([
  16240. BABYLON.serialize()
  16241. ], Camera.prototype, "minZ", void 0);
  16242. __decorate([
  16243. BABYLON.serialize()
  16244. ], Camera.prototype, "maxZ", void 0);
  16245. __decorate([
  16246. BABYLON.serialize()
  16247. ], Camera.prototype, "inertia", void 0);
  16248. __decorate([
  16249. BABYLON.serialize()
  16250. ], Camera.prototype, "mode", void 0);
  16251. __decorate([
  16252. BABYLON.serialize()
  16253. ], Camera.prototype, "layerMask", void 0);
  16254. __decorate([
  16255. BABYLON.serialize()
  16256. ], Camera.prototype, "fovMode", void 0);
  16257. __decorate([
  16258. BABYLON.serialize()
  16259. ], Camera.prototype, "cameraRigMode", void 0);
  16260. __decorate([
  16261. BABYLON.serialize()
  16262. ], Camera.prototype, "interaxialDistance", void 0);
  16263. __decorate([
  16264. BABYLON.serialize()
  16265. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16266. BABYLON.Camera = Camera;
  16267. })(BABYLON || (BABYLON = {}));
  16268. //# sourceMappingURL=babylon.camera.js.map
  16269. var BABYLON;
  16270. (function (BABYLON) {
  16271. BABYLON.CameraInputTypes = {};
  16272. var CameraInputsManager = (function () {
  16273. function CameraInputsManager(camera) {
  16274. this.attached = {};
  16275. this.camera = camera;
  16276. this.checkInputs = function () { };
  16277. }
  16278. CameraInputsManager.prototype.add = function (input) {
  16279. var type = input.getSimpleName();
  16280. if (this.attached[type]) {
  16281. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16282. return;
  16283. }
  16284. this.attached[type] = input;
  16285. input.camera = this.camera;
  16286. //for checkInputs, we are dynamically creating a function
  16287. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16288. if (input.checkInputs) {
  16289. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16290. }
  16291. if (this.attachedElement) {
  16292. input.attachControl(this.attachedElement);
  16293. }
  16294. };
  16295. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16296. for (var cam in this.attached) {
  16297. var input = this.attached[cam];
  16298. if (input === inputToRemove) {
  16299. input.detachControl(this.attachedElement);
  16300. delete this.attached[cam];
  16301. this.rebuildInputCheck();
  16302. }
  16303. }
  16304. };
  16305. CameraInputsManager.prototype.removeByType = function (inputType) {
  16306. for (var cam in this.attached) {
  16307. var input = this.attached[cam];
  16308. if (input.getTypeName() === inputType) {
  16309. input.detachControl(this.attachedElement);
  16310. delete this.attached[cam];
  16311. this.rebuildInputCheck();
  16312. }
  16313. }
  16314. };
  16315. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16316. var current = this.checkInputs;
  16317. return function () {
  16318. current();
  16319. fn();
  16320. };
  16321. };
  16322. CameraInputsManager.prototype.attachInput = function (input) {
  16323. input.attachControl(this.attachedElement, this.noPreventDefault);
  16324. };
  16325. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16326. if (this.attachedElement) {
  16327. return;
  16328. }
  16329. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16330. this.attachedElement = element;
  16331. this.noPreventDefault = noPreventDefault;
  16332. for (var cam in this.attached) {
  16333. var input = this.attached[cam];
  16334. this.attached[cam].attachControl(element, noPreventDefault);
  16335. }
  16336. };
  16337. CameraInputsManager.prototype.detachElement = function (element) {
  16338. if (this.attachedElement !== element) {
  16339. return;
  16340. }
  16341. for (var cam in this.attached) {
  16342. var input = this.attached[cam];
  16343. this.attached[cam].detachControl(element);
  16344. }
  16345. this.attachedElement = null;
  16346. };
  16347. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16348. this.checkInputs = function () { };
  16349. for (var cam in this.attached) {
  16350. var input = this.attached[cam];
  16351. if (input.checkInputs) {
  16352. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16353. }
  16354. }
  16355. };
  16356. CameraInputsManager.prototype.clear = function () {
  16357. if (this.attachedElement) {
  16358. this.detachElement(this.attachedElement);
  16359. }
  16360. this.attached = {};
  16361. this.attachedElement = null;
  16362. this.checkInputs = function () { };
  16363. };
  16364. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16365. var inputs = {};
  16366. for (var cam in this.attached) {
  16367. var input = this.attached[cam];
  16368. var res = BABYLON.SerializationHelper.Serialize(input);
  16369. inputs[input.getTypeName()] = res;
  16370. }
  16371. serializedCamera.inputsmgr = inputs;
  16372. };
  16373. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16374. var parsedInputs = parsedCamera.inputsmgr;
  16375. if (parsedInputs) {
  16376. this.clear();
  16377. for (var n in parsedInputs) {
  16378. var construct = BABYLON.CameraInputTypes[n];
  16379. if (construct) {
  16380. var parsedinput = parsedInputs[n];
  16381. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16382. this.add(input);
  16383. }
  16384. }
  16385. }
  16386. else {
  16387. //2016-03-08 this part is for managing backward compatibility
  16388. for (var n in this.attached) {
  16389. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16390. if (construct) {
  16391. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16392. this.remove(this.attached[n]);
  16393. this.add(input);
  16394. }
  16395. }
  16396. }
  16397. };
  16398. return CameraInputsManager;
  16399. }());
  16400. BABYLON.CameraInputsManager = CameraInputsManager;
  16401. })(BABYLON || (BABYLON = {}));
  16402. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16403. var BABYLON;
  16404. (function (BABYLON) {
  16405. var FreeCameraMouseInput = (function () {
  16406. function FreeCameraMouseInput(touchEnabled) {
  16407. if (touchEnabled === void 0) { touchEnabled = true; }
  16408. this.touchEnabled = touchEnabled;
  16409. this.buttons = [0, 1, 2];
  16410. this.angularSensibility = 2000.0;
  16411. }
  16412. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16413. var _this = this;
  16414. var engine = this.camera.getEngine();
  16415. if (!this._pointerInput) {
  16416. this._pointerInput = function (p, s) {
  16417. var evt = p.event;
  16418. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16419. return;
  16420. }
  16421. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16422. return;
  16423. }
  16424. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16425. try {
  16426. evt.srcElement.setPointerCapture(evt.pointerId);
  16427. }
  16428. catch (e) {
  16429. }
  16430. _this.previousPosition = {
  16431. x: evt.clientX,
  16432. y: evt.clientY
  16433. };
  16434. if (!noPreventDefault) {
  16435. evt.preventDefault();
  16436. element.focus();
  16437. }
  16438. }
  16439. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16440. try {
  16441. evt.srcElement.releasePointerCapture(evt.pointerId);
  16442. }
  16443. catch (e) {
  16444. }
  16445. _this.previousPosition = null;
  16446. if (!noPreventDefault) {
  16447. evt.preventDefault();
  16448. }
  16449. }
  16450. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16451. if (!_this.previousPosition || engine.isPointerLock) {
  16452. return;
  16453. }
  16454. var offsetX = evt.clientX - _this.previousPosition.x;
  16455. var offsetY = evt.clientY - _this.previousPosition.y;
  16456. if (_this.camera.getScene().useRightHandedSystem) {
  16457. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16458. }
  16459. else {
  16460. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16461. }
  16462. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16463. _this.previousPosition = {
  16464. x: evt.clientX,
  16465. y: evt.clientY
  16466. };
  16467. if (!noPreventDefault) {
  16468. evt.preventDefault();
  16469. }
  16470. }
  16471. };
  16472. }
  16473. this._onMouseMove = function (evt) {
  16474. if (!engine.isPointerLock) {
  16475. return;
  16476. }
  16477. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16478. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16479. if (_this.camera.getScene().useRightHandedSystem) {
  16480. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16481. }
  16482. else {
  16483. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16484. }
  16485. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16486. _this.previousPosition = null;
  16487. if (!noPreventDefault) {
  16488. evt.preventDefault();
  16489. }
  16490. };
  16491. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16492. element.addEventListener("mousemove", this._onMouseMove, false);
  16493. };
  16494. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16495. if (this._observer && element) {
  16496. this.camera.getScene().onPointerObservable.remove(this._observer);
  16497. element.removeEventListener("mousemove", this._onMouseMove);
  16498. this._observer = null;
  16499. this._onMouseMove = null;
  16500. this.previousPosition = null;
  16501. }
  16502. };
  16503. FreeCameraMouseInput.prototype.getTypeName = function () {
  16504. return "FreeCameraMouseInput";
  16505. };
  16506. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16507. return "mouse";
  16508. };
  16509. return FreeCameraMouseInput;
  16510. }());
  16511. __decorate([
  16512. BABYLON.serialize()
  16513. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16514. __decorate([
  16515. BABYLON.serialize()
  16516. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16517. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16518. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16519. })(BABYLON || (BABYLON = {}));
  16520. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16521. var BABYLON;
  16522. (function (BABYLON) {
  16523. var FreeCameraKeyboardMoveInput = (function () {
  16524. function FreeCameraKeyboardMoveInput() {
  16525. this._keys = [];
  16526. this.keysUp = [38];
  16527. this.keysDown = [40];
  16528. this.keysLeft = [37];
  16529. this.keysRight = [39];
  16530. }
  16531. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16532. var _this = this;
  16533. if (!this._onKeyDown) {
  16534. element.tabIndex = 1;
  16535. this._onKeyDown = function (evt) {
  16536. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16537. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16538. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16539. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16540. var index = _this._keys.indexOf(evt.keyCode);
  16541. if (index === -1) {
  16542. _this._keys.push(evt.keyCode);
  16543. }
  16544. if (!noPreventDefault) {
  16545. evt.preventDefault();
  16546. }
  16547. }
  16548. };
  16549. this._onKeyUp = function (evt) {
  16550. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16551. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16552. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16553. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16554. var index = _this._keys.indexOf(evt.keyCode);
  16555. if (index >= 0) {
  16556. _this._keys.splice(index, 1);
  16557. }
  16558. if (!noPreventDefault) {
  16559. evt.preventDefault();
  16560. }
  16561. }
  16562. };
  16563. element.addEventListener("keydown", this._onKeyDown, false);
  16564. element.addEventListener("keyup", this._onKeyUp, false);
  16565. BABYLON.Tools.RegisterTopRootEvents([
  16566. { name: "blur", handler: this._onLostFocus }
  16567. ]);
  16568. }
  16569. };
  16570. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16571. if (this._onKeyDown) {
  16572. element.removeEventListener("keydown", this._onKeyDown);
  16573. element.removeEventListener("keyup", this._onKeyUp);
  16574. BABYLON.Tools.UnregisterTopRootEvents([
  16575. { name: "blur", handler: this._onLostFocus }
  16576. ]);
  16577. this._keys = [];
  16578. this._onKeyDown = null;
  16579. this._onKeyUp = null;
  16580. }
  16581. };
  16582. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16583. if (this._onKeyDown) {
  16584. var camera = this.camera;
  16585. // Keyboard
  16586. for (var index = 0; index < this._keys.length; index++) {
  16587. var keyCode = this._keys[index];
  16588. var speed = camera._computeLocalCameraSpeed();
  16589. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16590. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16591. }
  16592. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16593. camera._localDirection.copyFromFloats(0, 0, speed);
  16594. }
  16595. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16596. camera._localDirection.copyFromFloats(speed, 0, 0);
  16597. }
  16598. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16599. camera._localDirection.copyFromFloats(0, 0, -speed);
  16600. }
  16601. if (camera.getScene().useRightHandedSystem) {
  16602. camera._localDirection.z *= -1;
  16603. }
  16604. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16605. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16606. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16607. }
  16608. }
  16609. };
  16610. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16611. return "FreeCameraKeyboardMoveInput";
  16612. };
  16613. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16614. this._keys = [];
  16615. };
  16616. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16617. return "keyboard";
  16618. };
  16619. return FreeCameraKeyboardMoveInput;
  16620. }());
  16621. __decorate([
  16622. BABYLON.serialize()
  16623. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16624. __decorate([
  16625. BABYLON.serialize()
  16626. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16627. __decorate([
  16628. BABYLON.serialize()
  16629. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16630. __decorate([
  16631. BABYLON.serialize()
  16632. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16633. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16634. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16635. })(BABYLON || (BABYLON = {}));
  16636. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16637. var BABYLON;
  16638. (function (BABYLON) {
  16639. var FreeCameraTouchInput = (function () {
  16640. function FreeCameraTouchInput() {
  16641. this._offsetX = null;
  16642. this._offsetY = null;
  16643. this._pointerCount = 0;
  16644. this._pointerPressed = [];
  16645. this.touchAngularSensibility = 200000.0;
  16646. this.touchMoveSensibility = 250.0;
  16647. }
  16648. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16649. var _this = this;
  16650. var previousPosition;
  16651. if (this._pointerInput === undefined) {
  16652. this._onLostFocus = function (evt) {
  16653. _this._offsetX = null;
  16654. _this._offsetY = null;
  16655. };
  16656. this._pointerInput = function (p, s) {
  16657. var evt = p.event;
  16658. if (evt.pointerType === "mouse") {
  16659. return;
  16660. }
  16661. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16662. if (!noPreventDefault) {
  16663. evt.preventDefault();
  16664. }
  16665. _this._pointerPressed.push(evt.pointerId);
  16666. if (_this._pointerPressed.length !== 1) {
  16667. return;
  16668. }
  16669. previousPosition = {
  16670. x: evt.clientX,
  16671. y: evt.clientY
  16672. };
  16673. }
  16674. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16675. if (!noPreventDefault) {
  16676. evt.preventDefault();
  16677. }
  16678. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16679. if (index === -1) {
  16680. return;
  16681. }
  16682. _this._pointerPressed.splice(index, 1);
  16683. if (index != 0) {
  16684. return;
  16685. }
  16686. previousPosition = null;
  16687. _this._offsetX = null;
  16688. _this._offsetY = null;
  16689. }
  16690. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16691. if (!noPreventDefault) {
  16692. evt.preventDefault();
  16693. }
  16694. if (!previousPosition) {
  16695. return;
  16696. }
  16697. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16698. if (index != 0) {
  16699. return;
  16700. }
  16701. _this._offsetX = evt.clientX - previousPosition.x;
  16702. _this._offsetY = -(evt.clientY - previousPosition.y);
  16703. }
  16704. };
  16705. }
  16706. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16707. element.addEventListener("blur", this._onLostFocus);
  16708. };
  16709. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16710. if (this._pointerInput && element) {
  16711. this.camera.getScene().onPointerObservable.remove(this._observer);
  16712. this._observer = null;
  16713. element.removeEventListener("blur", this._onLostFocus);
  16714. this._onLostFocus = null;
  16715. this._pointerPressed = [];
  16716. this._offsetX = null;
  16717. this._offsetY = null;
  16718. this._pointerCount = 0;
  16719. }
  16720. };
  16721. FreeCameraTouchInput.prototype.checkInputs = function () {
  16722. if (this._offsetX) {
  16723. var camera = this.camera;
  16724. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16725. if (this._pointerPressed.length > 1) {
  16726. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16727. }
  16728. else {
  16729. var speed = camera._computeLocalCameraSpeed();
  16730. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16731. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16732. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16733. }
  16734. }
  16735. };
  16736. FreeCameraTouchInput.prototype.getTypeName = function () {
  16737. return "FreeCameraTouchInput";
  16738. };
  16739. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16740. return "touch";
  16741. };
  16742. return FreeCameraTouchInput;
  16743. }());
  16744. __decorate([
  16745. BABYLON.serialize()
  16746. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16747. __decorate([
  16748. BABYLON.serialize()
  16749. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16750. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16751. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16752. })(BABYLON || (BABYLON = {}));
  16753. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16754. var BABYLON;
  16755. (function (BABYLON) {
  16756. var FreeCameraDeviceOrientationInput = (function () {
  16757. function FreeCameraDeviceOrientationInput() {
  16758. var _this = this;
  16759. this._screenOrientationAngle = 0;
  16760. this._screenQuaternion = new BABYLON.Quaternion();
  16761. this._alpha = 0;
  16762. this._beta = 0;
  16763. this._gamma = 0;
  16764. this._orientationChanged = function () {
  16765. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16766. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16767. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16768. };
  16769. this._deviceOrientation = function (evt) {
  16770. _this._alpha = evt.alpha;
  16771. _this._beta = evt.beta;
  16772. _this._gamma = evt.gamma;
  16773. };
  16774. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16775. this._orientationChanged();
  16776. }
  16777. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16778. get: function () {
  16779. return this._camera;
  16780. },
  16781. set: function (camera) {
  16782. this._camera = camera;
  16783. if (!this._camera.rotationQuaternion)
  16784. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16785. },
  16786. enumerable: true,
  16787. configurable: true
  16788. });
  16789. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16790. window.addEventListener("orientationchange", this._orientationChanged);
  16791. window.addEventListener("deviceorientation", this._deviceOrientation);
  16792. //In certain cases, the attach control is called AFTER orientation was changed,
  16793. //So this is needed.
  16794. this._orientationChanged();
  16795. };
  16796. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16797. window.removeEventListener("orientationchange", this._orientationChanged);
  16798. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16799. };
  16800. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16801. //if no device orientation provided, don't update the rotation.
  16802. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16803. if (!this._alpha)
  16804. return;
  16805. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16806. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16807. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16808. //Mirror on XY Plane
  16809. this._camera.rotationQuaternion.z *= -1;
  16810. this._camera.rotationQuaternion.w *= -1;
  16811. };
  16812. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  16813. return "FreeCameraDeviceOrientationInput";
  16814. };
  16815. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  16816. return "deviceOrientation";
  16817. };
  16818. return FreeCameraDeviceOrientationInput;
  16819. }());
  16820. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  16821. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  16822. })(BABYLON || (BABYLON = {}));
  16823. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  16824. var BABYLON;
  16825. (function (BABYLON) {
  16826. var FreeCameraGamepadInput = (function () {
  16827. function FreeCameraGamepadInput() {
  16828. this.gamepadAngularSensibility = 200;
  16829. this.gamepadMoveSensibility = 40;
  16830. // private members
  16831. this._cameraTransform = BABYLON.Matrix.Identity();
  16832. this._deltaTransform = BABYLON.Vector3.Zero();
  16833. this._vector3 = BABYLON.Vector3.Zero();
  16834. this._vector2 = BABYLON.Vector2.Zero();
  16835. }
  16836. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  16837. var _this = this;
  16838. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  16839. };
  16840. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  16841. if (this._gamepads) {
  16842. this._gamepads.dispose();
  16843. }
  16844. this.gamepad = null;
  16845. };
  16846. FreeCameraGamepadInput.prototype.checkInputs = function () {
  16847. if (this.gamepad) {
  16848. var camera = this.camera;
  16849. var LSValues = this.gamepad.leftStick;
  16850. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  16851. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  16852. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  16853. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  16854. var RSValues = this.gamepad.rightStick;
  16855. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  16856. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  16857. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  16858. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  16859. if (!camera.rotationQuaternion) {
  16860. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  16861. }
  16862. else {
  16863. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  16864. }
  16865. var speed = camera._computeLocalCameraSpeed() * 50.0;
  16866. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  16867. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  16868. camera.cameraDirection.addInPlace(this._deltaTransform);
  16869. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  16870. camera.cameraRotation.addInPlace(this._vector2);
  16871. }
  16872. };
  16873. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  16874. // Only the first gamepad found can control the camera
  16875. if (!this.gamepad && gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  16876. this.gamepad = gamepad;
  16877. }
  16878. };
  16879. FreeCameraGamepadInput.prototype.getTypeName = function () {
  16880. return "FreeCameraGamepadInput";
  16881. };
  16882. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  16883. return "gamepad";
  16884. };
  16885. return FreeCameraGamepadInput;
  16886. }());
  16887. __decorate([
  16888. BABYLON.serialize()
  16889. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  16890. __decorate([
  16891. BABYLON.serialize()
  16892. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  16893. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  16894. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  16895. })(BABYLON || (BABYLON = {}));
  16896. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  16897. var BABYLON;
  16898. (function (BABYLON) {
  16899. var ArcRotateCameraKeyboardMoveInput = (function () {
  16900. function ArcRotateCameraKeyboardMoveInput() {
  16901. this._keys = [];
  16902. this.keysUp = [38];
  16903. this.keysDown = [40];
  16904. this.keysLeft = [37];
  16905. this.keysRight = [39];
  16906. }
  16907. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16908. var _this = this;
  16909. element.tabIndex = 1;
  16910. this._onKeyDown = function (evt) {
  16911. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16912. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16913. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16914. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16915. var index = _this._keys.indexOf(evt.keyCode);
  16916. if (index === -1) {
  16917. _this._keys.push(evt.keyCode);
  16918. }
  16919. if (evt.preventDefault) {
  16920. if (!noPreventDefault) {
  16921. evt.preventDefault();
  16922. }
  16923. }
  16924. }
  16925. };
  16926. this._onKeyUp = function (evt) {
  16927. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16928. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16929. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16930. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16931. var index = _this._keys.indexOf(evt.keyCode);
  16932. if (index >= 0) {
  16933. _this._keys.splice(index, 1);
  16934. }
  16935. if (evt.preventDefault) {
  16936. if (!noPreventDefault) {
  16937. evt.preventDefault();
  16938. }
  16939. }
  16940. }
  16941. };
  16942. this._onLostFocus = function () {
  16943. _this._keys = [];
  16944. };
  16945. element.addEventListener("keydown", this._onKeyDown, false);
  16946. element.addEventListener("keyup", this._onKeyUp, false);
  16947. BABYLON.Tools.RegisterTopRootEvents([
  16948. { name: "blur", handler: this._onLostFocus }
  16949. ]);
  16950. };
  16951. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16952. if (element) {
  16953. element.removeEventListener("keydown", this._onKeyDown);
  16954. element.removeEventListener("keyup", this._onKeyUp);
  16955. }
  16956. BABYLON.Tools.UnregisterTopRootEvents([
  16957. { name: "blur", handler: this._onLostFocus }
  16958. ]);
  16959. this._keys = [];
  16960. this._onKeyDown = null;
  16961. this._onKeyUp = null;
  16962. this._onLostFocus = null;
  16963. };
  16964. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16965. if (this._onKeyDown) {
  16966. var camera = this.camera;
  16967. for (var index = 0; index < this._keys.length; index++) {
  16968. var keyCode = this._keys[index];
  16969. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16970. camera.inertialAlphaOffset -= 0.01;
  16971. }
  16972. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16973. camera.inertialBetaOffset -= 0.01;
  16974. }
  16975. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16976. camera.inertialAlphaOffset += 0.01;
  16977. }
  16978. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16979. camera.inertialBetaOffset += 0.01;
  16980. }
  16981. }
  16982. }
  16983. };
  16984. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16985. return "ArcRotateCameraKeyboardMoveInput";
  16986. };
  16987. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16988. return "keyboard";
  16989. };
  16990. return ArcRotateCameraKeyboardMoveInput;
  16991. }());
  16992. __decorate([
  16993. BABYLON.serialize()
  16994. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16995. __decorate([
  16996. BABYLON.serialize()
  16997. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16998. __decorate([
  16999. BABYLON.serialize()
  17000. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17001. __decorate([
  17002. BABYLON.serialize()
  17003. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17004. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17005. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17006. })(BABYLON || (BABYLON = {}));
  17007. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17008. var BABYLON;
  17009. (function (BABYLON) {
  17010. var ArcRotateCameraMouseWheelInput = (function () {
  17011. function ArcRotateCameraMouseWheelInput() {
  17012. this.wheelPrecision = 3.0;
  17013. }
  17014. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17015. var _this = this;
  17016. this._wheel = function (p, s) {
  17017. //sanity check - this should be a PointerWheel event.
  17018. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17019. return;
  17020. var event = p.event;
  17021. var delta = 0;
  17022. if (event.wheelDelta) {
  17023. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17024. }
  17025. else if (event.detail) {
  17026. delta = -event.detail / _this.wheelPrecision;
  17027. }
  17028. if (delta)
  17029. _this.camera.inertialRadiusOffset += delta;
  17030. if (event.preventDefault) {
  17031. if (!noPreventDefault) {
  17032. event.preventDefault();
  17033. }
  17034. }
  17035. };
  17036. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17037. };
  17038. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17039. if (this._observer && element) {
  17040. this.camera.getScene().onPointerObservable.remove(this._observer);
  17041. this._observer = null;
  17042. this._wheel = null;
  17043. }
  17044. };
  17045. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17046. return "ArcRotateCameraMouseWheelInput";
  17047. };
  17048. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17049. return "mousewheel";
  17050. };
  17051. return ArcRotateCameraMouseWheelInput;
  17052. }());
  17053. __decorate([
  17054. BABYLON.serialize()
  17055. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17056. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17057. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17058. })(BABYLON || (BABYLON = {}));
  17059. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17060. var BABYLON;
  17061. (function (BABYLON) {
  17062. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17063. var ArcRotateCameraPointersInput = (function () {
  17064. function ArcRotateCameraPointersInput() {
  17065. this.buttons = [0, 1, 2];
  17066. this.angularSensibilityX = 1000.0;
  17067. this.angularSensibilityY = 1000.0;
  17068. this.pinchPrecision = 6.0;
  17069. this.panningSensibility = 50.0;
  17070. this._isPanClick = false;
  17071. this.pinchInwards = true;
  17072. }
  17073. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17074. var _this = this;
  17075. var engine = this.camera.getEngine();
  17076. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17077. var pointA, pointB;
  17078. var previousPinchDistance = 0;
  17079. this._pointerInput = function (p, s) {
  17080. var evt = p.event;
  17081. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17082. return;
  17083. }
  17084. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17085. try {
  17086. evt.srcElement.setPointerCapture(evt.pointerId);
  17087. }
  17088. catch (e) {
  17089. }
  17090. // Manage panning with pan button click
  17091. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17092. // manage pointers
  17093. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17094. if (pointA === undefined) {
  17095. pointA = cacheSoloPointer;
  17096. }
  17097. else if (pointB === undefined) {
  17098. pointB = cacheSoloPointer;
  17099. }
  17100. if (!noPreventDefault) {
  17101. evt.preventDefault();
  17102. element.focus();
  17103. }
  17104. }
  17105. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17106. try {
  17107. evt.srcElement.releasePointerCapture(evt.pointerId);
  17108. }
  17109. catch (e) {
  17110. }
  17111. cacheSoloPointer = null;
  17112. previousPinchDistance = 0;
  17113. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17114. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17115. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17116. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17117. pointA = pointB = undefined;
  17118. if (!noPreventDefault) {
  17119. evt.preventDefault();
  17120. }
  17121. }
  17122. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17123. if (!noPreventDefault) {
  17124. evt.preventDefault();
  17125. }
  17126. // One button down
  17127. if (pointA && pointB === undefined) {
  17128. if (_this.panningSensibility !== 0 &&
  17129. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17130. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17131. _this.camera
  17132. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17133. _this.camera
  17134. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17135. }
  17136. else {
  17137. var offsetX = evt.clientX - cacheSoloPointer.x;
  17138. var offsetY = evt.clientY - cacheSoloPointer.y;
  17139. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17140. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17141. }
  17142. cacheSoloPointer.x = evt.clientX;
  17143. cacheSoloPointer.y = evt.clientY;
  17144. }
  17145. else if (pointA && pointB) {
  17146. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17147. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17148. ed.x = evt.clientX;
  17149. ed.y = evt.clientY;
  17150. var direction = _this.pinchInwards ? 1 : -1;
  17151. var distX = pointA.x - pointB.x;
  17152. var distY = pointA.y - pointB.y;
  17153. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17154. if (previousPinchDistance === 0) {
  17155. previousPinchDistance = pinchSquaredDistance;
  17156. return;
  17157. }
  17158. if (pinchSquaredDistance !== previousPinchDistance) {
  17159. _this.camera
  17160. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17161. (_this.pinchPrecision *
  17162. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17163. direction);
  17164. previousPinchDistance = pinchSquaredDistance;
  17165. }
  17166. }
  17167. }
  17168. };
  17169. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17170. this._onContextMenu = function (evt) {
  17171. evt.preventDefault();
  17172. };
  17173. if (!this.camera._useCtrlForPanning) {
  17174. element.addEventListener("contextmenu", this._onContextMenu, false);
  17175. }
  17176. this._onLostFocus = function () {
  17177. //this._keys = [];
  17178. pointA = pointB = undefined;
  17179. previousPinchDistance = 0;
  17180. cacheSoloPointer = null;
  17181. };
  17182. this._onMouseMove = function (evt) {
  17183. if (!engine.isPointerLock) {
  17184. return;
  17185. }
  17186. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17187. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17188. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17189. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17190. if (!noPreventDefault) {
  17191. evt.preventDefault();
  17192. }
  17193. };
  17194. this._onGestureStart = function (e) {
  17195. if (window.MSGesture === undefined) {
  17196. return;
  17197. }
  17198. if (!_this._MSGestureHandler) {
  17199. _this._MSGestureHandler = new MSGesture();
  17200. _this._MSGestureHandler.target = element;
  17201. }
  17202. _this._MSGestureHandler.addPointer(e.pointerId);
  17203. };
  17204. this._onGesture = function (e) {
  17205. _this.camera.radius *= e.scale;
  17206. if (e.preventDefault) {
  17207. if (!noPreventDefault) {
  17208. e.stopPropagation();
  17209. e.preventDefault();
  17210. }
  17211. }
  17212. };
  17213. element.addEventListener("mousemove", this._onMouseMove, false);
  17214. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17215. element.addEventListener("MSGestureChange", this._onGesture, false);
  17216. element.addEventListener("keydown", this._onKeyDown, false);
  17217. element.addEventListener("keyup", this._onKeyUp, false);
  17218. BABYLON.Tools.RegisterTopRootEvents([
  17219. { name: "blur", handler: this._onLostFocus }
  17220. ]);
  17221. };
  17222. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17223. if (element && this._observer) {
  17224. this.camera.getScene().onPointerObservable.remove(this._observer);
  17225. this._observer = null;
  17226. element.removeEventListener("contextmenu", this._onContextMenu);
  17227. element.removeEventListener("mousemove", this._onMouseMove);
  17228. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17229. element.removeEventListener("MSGestureChange", this._onGesture);
  17230. element.removeEventListener("keydown", this._onKeyDown);
  17231. element.removeEventListener("keyup", this._onKeyUp);
  17232. this._isPanClick = false;
  17233. this.pinchInwards = true;
  17234. this._onKeyDown = null;
  17235. this._onKeyUp = null;
  17236. this._onMouseMove = null;
  17237. this._onGestureStart = null;
  17238. this._onGesture = null;
  17239. this._MSGestureHandler = null;
  17240. this._onLostFocus = null;
  17241. this._onContextMenu = null;
  17242. }
  17243. BABYLON.Tools.UnregisterTopRootEvents([
  17244. { name: "blur", handler: this._onLostFocus }
  17245. ]);
  17246. };
  17247. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17248. return "ArcRotateCameraPointersInput";
  17249. };
  17250. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17251. return "pointers";
  17252. };
  17253. return ArcRotateCameraPointersInput;
  17254. }());
  17255. __decorate([
  17256. BABYLON.serialize()
  17257. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17258. __decorate([
  17259. BABYLON.serialize()
  17260. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17261. __decorate([
  17262. BABYLON.serialize()
  17263. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17264. __decorate([
  17265. BABYLON.serialize()
  17266. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17267. __decorate([
  17268. BABYLON.serialize()
  17269. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17270. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17271. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17272. })(BABYLON || (BABYLON = {}));
  17273. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17274. var BABYLON;
  17275. (function (BABYLON) {
  17276. var ArcRotateCameraGamepadInput = (function () {
  17277. function ArcRotateCameraGamepadInput() {
  17278. this.gamepadRotationSensibility = 80;
  17279. this.gamepadMoveSensibility = 40;
  17280. }
  17281. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17282. var _this = this;
  17283. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17284. };
  17285. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17286. if (this._gamepads) {
  17287. this._gamepads.dispose();
  17288. }
  17289. this.gamepad = null;
  17290. };
  17291. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17292. if (this.gamepad) {
  17293. var camera = this.camera;
  17294. var RSValues = this.gamepad.rightStick;
  17295. if (RSValues.x != 0) {
  17296. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17297. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17298. camera.inertialAlphaOffset += normalizedRX;
  17299. }
  17300. }
  17301. if (RSValues.y != 0) {
  17302. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17303. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17304. camera.inertialBetaOffset += normalizedRY;
  17305. }
  17306. }
  17307. var LSValues = this.gamepad.leftStick;
  17308. if (LSValues.y != 0) {
  17309. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17310. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17311. this.camera.inertialRadiusOffset -= normalizedLY;
  17312. }
  17313. }
  17314. }
  17315. };
  17316. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17317. // Only the first gamepad can control the camera
  17318. if (!this.gamepad && gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17319. this.gamepad = gamepad;
  17320. }
  17321. };
  17322. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17323. return "ArcRotateCameraGamepadInput";
  17324. };
  17325. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17326. return "gamepad";
  17327. };
  17328. return ArcRotateCameraGamepadInput;
  17329. }());
  17330. __decorate([
  17331. BABYLON.serialize()
  17332. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17333. __decorate([
  17334. BABYLON.serialize()
  17335. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17336. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17337. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17338. })(BABYLON || (BABYLON = {}));
  17339. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17340. var BABYLON;
  17341. (function (BABYLON) {
  17342. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17343. function ArcRotateCameraVRDeviceOrientationInput() {
  17344. this.alphaCorrection = 1;
  17345. this.betaCorrection = 1;
  17346. this.gammaCorrection = 1;
  17347. this._alpha = 0;
  17348. this._beta = 0;
  17349. this._gamma = 0;
  17350. this._dirty = false;
  17351. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17352. }
  17353. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17354. this.camera.attachControl(element, noPreventDefault);
  17355. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17356. };
  17357. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17358. var camera = this.camera;
  17359. this._alpha = +evt.alpha | 0;
  17360. this._beta = +evt.beta | 0;
  17361. this._gamma = +evt.gamma | 0;
  17362. this._dirty = true;
  17363. };
  17364. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17365. if (this._dirty) {
  17366. this._dirty = false;
  17367. if (this._gamma < 0) {
  17368. this._gamma = 180 + this._gamma;
  17369. }
  17370. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17371. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17372. }
  17373. };
  17374. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17375. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17376. };
  17377. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17378. return "ArcRotateCameraVRDeviceOrientationInput";
  17379. };
  17380. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17381. return "VRDeviceOrientation";
  17382. };
  17383. return ArcRotateCameraVRDeviceOrientationInput;
  17384. }());
  17385. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17386. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17387. })(BABYLON || (BABYLON = {}));
  17388. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17389. /// <reference path="babylon.camera.ts" />
  17390. var BABYLON;
  17391. (function (BABYLON) {
  17392. var TargetCamera = (function (_super) {
  17393. __extends(TargetCamera, _super);
  17394. function TargetCamera(name, position, scene) {
  17395. var _this = _super.call(this, name, position, scene) || this;
  17396. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17397. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17398. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17399. _this.speed = 2.0;
  17400. _this.noRotationConstraint = false;
  17401. _this.lockedTarget = null;
  17402. _this._currentTarget = BABYLON.Vector3.Zero();
  17403. _this._viewMatrix = BABYLON.Matrix.Zero();
  17404. _this._camMatrix = BABYLON.Matrix.Zero();
  17405. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17406. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17407. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17408. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17409. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17410. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17411. _this._tempMatrix = BABYLON.Matrix.Zero();
  17412. return _this;
  17413. }
  17414. TargetCamera.prototype.getFrontPosition = function (distance) {
  17415. var direction = this.getTarget().subtract(this.position);
  17416. direction.normalize();
  17417. direction.scaleInPlace(distance);
  17418. return this.globalPosition.add(direction);
  17419. };
  17420. TargetCamera.prototype._getLockedTargetPosition = function () {
  17421. if (!this.lockedTarget) {
  17422. return null;
  17423. }
  17424. if (this.lockedTarget.absolutePosition) {
  17425. this.lockedTarget.computeWorldMatrix();
  17426. }
  17427. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17428. };
  17429. // Cache
  17430. TargetCamera.prototype._initCache = function () {
  17431. _super.prototype._initCache.call(this);
  17432. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17433. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17434. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17435. };
  17436. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17437. if (!ignoreParentClass) {
  17438. _super.prototype._updateCache.call(this);
  17439. }
  17440. var lockedTargetPosition = this._getLockedTargetPosition();
  17441. if (!lockedTargetPosition) {
  17442. this._cache.lockedTarget = null;
  17443. }
  17444. else {
  17445. if (!this._cache.lockedTarget) {
  17446. this._cache.lockedTarget = lockedTargetPosition.clone();
  17447. }
  17448. else {
  17449. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17450. }
  17451. }
  17452. this._cache.rotation.copyFrom(this.rotation);
  17453. if (this.rotationQuaternion)
  17454. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17455. };
  17456. // Synchronized
  17457. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17458. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17459. return false;
  17460. }
  17461. var lockedTargetPosition = this._getLockedTargetPosition();
  17462. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17463. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17464. };
  17465. // Methods
  17466. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17467. var engine = this.getEngine();
  17468. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17469. };
  17470. // Target
  17471. TargetCamera.prototype.setTarget = function (target) {
  17472. this.upVector.normalize();
  17473. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17474. this._camMatrix.invert();
  17475. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17476. var vDir = target.subtract(this.position);
  17477. if (vDir.x >= 0.0) {
  17478. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17479. }
  17480. else {
  17481. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17482. }
  17483. this.rotation.z = 0;
  17484. if (isNaN(this.rotation.x)) {
  17485. this.rotation.x = 0;
  17486. }
  17487. if (isNaN(this.rotation.y)) {
  17488. this.rotation.y = 0;
  17489. }
  17490. if (isNaN(this.rotation.z)) {
  17491. this.rotation.z = 0;
  17492. }
  17493. if (this.rotationQuaternion) {
  17494. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17495. }
  17496. };
  17497. /**
  17498. * Return the current target position of the camera. This value is expressed in local space.
  17499. */
  17500. TargetCamera.prototype.getTarget = function () {
  17501. return this._currentTarget;
  17502. };
  17503. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17504. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17505. };
  17506. TargetCamera.prototype._updatePosition = function () {
  17507. if (this.parent) {
  17508. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  17509. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  17510. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  17511. return;
  17512. }
  17513. this.position.addInPlace(this.cameraDirection);
  17514. };
  17515. TargetCamera.prototype._checkInputs = function () {
  17516. var needToMove = this._decideIfNeedsToMove();
  17517. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17518. // Move
  17519. if (needToMove) {
  17520. this._updatePosition();
  17521. }
  17522. // Rotate
  17523. if (needToRotate) {
  17524. this.rotation.x += this.cameraRotation.x;
  17525. this.rotation.y += this.cameraRotation.y;
  17526. if (!this.noRotationConstraint) {
  17527. var limit = (Math.PI / 2) * 0.95;
  17528. if (this.rotation.x > limit)
  17529. this.rotation.x = limit;
  17530. if (this.rotation.x < -limit)
  17531. this.rotation.x = -limit;
  17532. }
  17533. }
  17534. // Inertia
  17535. if (needToMove) {
  17536. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17537. this.cameraDirection.x = 0;
  17538. }
  17539. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17540. this.cameraDirection.y = 0;
  17541. }
  17542. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17543. this.cameraDirection.z = 0;
  17544. }
  17545. this.cameraDirection.scaleInPlace(this.inertia);
  17546. }
  17547. if (needToRotate) {
  17548. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17549. this.cameraRotation.x = 0;
  17550. }
  17551. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17552. this.cameraRotation.y = 0;
  17553. }
  17554. this.cameraRotation.scaleInPlace(this.inertia);
  17555. }
  17556. _super.prototype._checkInputs.call(this);
  17557. };
  17558. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17559. if (this.rotationQuaternion) {
  17560. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17561. //update the up vector!
  17562. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17563. }
  17564. else {
  17565. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17566. }
  17567. };
  17568. TargetCamera.prototype._getViewMatrix = function () {
  17569. if (!this.lockedTarget) {
  17570. // Compute
  17571. this._updateCameraRotationMatrix();
  17572. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17573. // Computing target and final matrix
  17574. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17575. }
  17576. else {
  17577. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17578. }
  17579. if (this.getScene().useRightHandedSystem) {
  17580. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17581. }
  17582. else {
  17583. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17584. }
  17585. return this._viewMatrix;
  17586. };
  17587. /**
  17588. * @override
  17589. * Override Camera.createRigCamera
  17590. */
  17591. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17592. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17593. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17594. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17595. if (!this.rotationQuaternion) {
  17596. this.rotationQuaternion = new BABYLON.Quaternion();
  17597. }
  17598. rigCamera._cameraRigParams = {};
  17599. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17600. }
  17601. return rigCamera;
  17602. }
  17603. return null;
  17604. };
  17605. /**
  17606. * @override
  17607. * Override Camera._updateRigCameras
  17608. */
  17609. TargetCamera.prototype._updateRigCameras = function () {
  17610. var camLeft = this._rigCameras[0];
  17611. var camRight = this._rigCameras[1];
  17612. switch (this.cameraRigMode) {
  17613. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17614. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17615. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17616. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17617. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17618. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17619. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17620. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17621. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17622. camLeft.setTarget(this.getTarget());
  17623. camRight.setTarget(this.getTarget());
  17624. break;
  17625. case BABYLON.Camera.RIG_MODE_VR:
  17626. case BABYLON.Camera.RIG_MODE_WEBVR:
  17627. if (camLeft.rotationQuaternion) {
  17628. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17629. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17630. }
  17631. else {
  17632. camLeft.rotation.copyFrom(this.rotation);
  17633. camRight.rotation.copyFrom(this.rotation);
  17634. }
  17635. camLeft.position.copyFrom(this.position);
  17636. camRight.position.copyFrom(this.position);
  17637. break;
  17638. }
  17639. _super.prototype._updateRigCameras.call(this);
  17640. };
  17641. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17642. if (!this._rigCamTransformMatrix) {
  17643. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17644. }
  17645. var target = this.getTarget();
  17646. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17647. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17648. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17649. };
  17650. TargetCamera.prototype.getClassName = function () {
  17651. return "TargetCamera";
  17652. };
  17653. return TargetCamera;
  17654. }(BABYLON.Camera));
  17655. __decorate([
  17656. BABYLON.serializeAsVector3()
  17657. ], TargetCamera.prototype, "rotation", void 0);
  17658. __decorate([
  17659. BABYLON.serialize()
  17660. ], TargetCamera.prototype, "speed", void 0);
  17661. __decorate([
  17662. BABYLON.serializeAsMeshReference("lockedTargetId")
  17663. ], TargetCamera.prototype, "lockedTarget", void 0);
  17664. BABYLON.TargetCamera = TargetCamera;
  17665. })(BABYLON || (BABYLON = {}));
  17666. //# sourceMappingURL=babylon.targetCamera.js.map
  17667. var BABYLON;
  17668. (function (BABYLON) {
  17669. var FreeCamera = (function (_super) {
  17670. __extends(FreeCamera, _super);
  17671. function FreeCamera(name, position, scene) {
  17672. var _this = _super.call(this, name, position, scene) || this;
  17673. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17674. _this.checkCollisions = false;
  17675. _this.applyGravity = false;
  17676. _this._collider = new BABYLON.Collider();
  17677. _this._needMoveForGravity = false;
  17678. _this._oldPosition = BABYLON.Vector3.Zero();
  17679. _this._diffPosition = BABYLON.Vector3.Zero();
  17680. _this._newPosition = BABYLON.Vector3.Zero();
  17681. // Collisions
  17682. _this._collisionMask = -1;
  17683. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17684. if (collidedMesh === void 0) { collidedMesh = null; }
  17685. //TODO move this to the collision coordinator!
  17686. if (_this.getScene().workerCollisions)
  17687. newPosition.multiplyInPlace(_this._collider.radius);
  17688. var updatePosition = function (newPos) {
  17689. _this._newPosition.copyFrom(newPos);
  17690. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17691. var oldPosition = _this.position.clone();
  17692. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17693. _this.position.addInPlace(_this._diffPosition);
  17694. if (_this.onCollide && collidedMesh) {
  17695. _this.onCollide(collidedMesh);
  17696. }
  17697. }
  17698. };
  17699. updatePosition(newPosition);
  17700. };
  17701. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17702. _this.inputs.addKeyboard().addMouse();
  17703. return _this;
  17704. }
  17705. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17706. //-- begin properties for backward compatibility for inputs
  17707. get: function () {
  17708. var mouse = this.inputs.attached["mouse"];
  17709. if (mouse)
  17710. return mouse.angularSensibility;
  17711. },
  17712. set: function (value) {
  17713. var mouse = this.inputs.attached["mouse"];
  17714. if (mouse)
  17715. mouse.angularSensibility = value;
  17716. },
  17717. enumerable: true,
  17718. configurable: true
  17719. });
  17720. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17721. get: function () {
  17722. var keyboard = this.inputs.attached["keyboard"];
  17723. if (keyboard)
  17724. return keyboard.keysUp;
  17725. },
  17726. set: function (value) {
  17727. var keyboard = this.inputs.attached["keyboard"];
  17728. if (keyboard)
  17729. keyboard.keysUp = value;
  17730. },
  17731. enumerable: true,
  17732. configurable: true
  17733. });
  17734. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17735. get: function () {
  17736. var keyboard = this.inputs.attached["keyboard"];
  17737. if (keyboard)
  17738. return keyboard.keysDown;
  17739. },
  17740. set: function (value) {
  17741. var keyboard = this.inputs.attached["keyboard"];
  17742. if (keyboard)
  17743. keyboard.keysDown = value;
  17744. },
  17745. enumerable: true,
  17746. configurable: true
  17747. });
  17748. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17749. get: function () {
  17750. var keyboard = this.inputs.attached["keyboard"];
  17751. if (keyboard)
  17752. return keyboard.keysLeft;
  17753. },
  17754. set: function (value) {
  17755. var keyboard = this.inputs.attached["keyboard"];
  17756. if (keyboard)
  17757. keyboard.keysLeft = value;
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17763. get: function () {
  17764. var keyboard = this.inputs.attached["keyboard"];
  17765. if (keyboard)
  17766. return keyboard.keysRight;
  17767. },
  17768. set: function (value) {
  17769. var keyboard = this.inputs.attached["keyboard"];
  17770. if (keyboard)
  17771. keyboard.keysRight = value;
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. // Controls
  17777. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17778. this.inputs.attachElement(element, noPreventDefault);
  17779. };
  17780. FreeCamera.prototype.detachControl = function (element) {
  17781. this.inputs.detachElement(element);
  17782. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17783. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17784. };
  17785. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17786. get: function () {
  17787. return this._collisionMask;
  17788. },
  17789. set: function (mask) {
  17790. this._collisionMask = !isNaN(mask) ? mask : -1;
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. FreeCamera.prototype._collideWithWorld = function (velocity) {
  17796. var globalPosition;
  17797. if (this.parent) {
  17798. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  17799. }
  17800. else {
  17801. globalPosition = this.position;
  17802. }
  17803. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  17804. this._collider.radius = this.ellipsoid;
  17805. this._collider.collisionMask = this._collisionMask;
  17806. //no need for clone, as long as gravity is not on.
  17807. var actualVelocity = velocity;
  17808. //add gravity to the velocity to prevent the dual-collision checking
  17809. if (this.applyGravity) {
  17810. //this prevents mending with cameraDirection, a global variable of the free camera class.
  17811. actualVelocity = velocity.add(this.getScene().gravity);
  17812. }
  17813. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  17814. };
  17815. FreeCamera.prototype._checkInputs = function () {
  17816. if (!this._localDirection) {
  17817. this._localDirection = BABYLON.Vector3.Zero();
  17818. this._transformedDirection = BABYLON.Vector3.Zero();
  17819. }
  17820. this.inputs.checkInputs();
  17821. _super.prototype._checkInputs.call(this);
  17822. };
  17823. FreeCamera.prototype._decideIfNeedsToMove = function () {
  17824. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17825. };
  17826. FreeCamera.prototype._updatePosition = function () {
  17827. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  17828. this._collideWithWorld(this.cameraDirection);
  17829. }
  17830. else {
  17831. _super.prototype._updatePosition.call(this);
  17832. }
  17833. };
  17834. FreeCamera.prototype.dispose = function () {
  17835. this.inputs.clear();
  17836. _super.prototype.dispose.call(this);
  17837. };
  17838. FreeCamera.prototype.getClassName = function () {
  17839. return "FreeCamera";
  17840. };
  17841. return FreeCamera;
  17842. }(BABYLON.TargetCamera));
  17843. __decorate([
  17844. BABYLON.serializeAsVector3()
  17845. ], FreeCamera.prototype, "ellipsoid", void 0);
  17846. __decorate([
  17847. BABYLON.serialize()
  17848. ], FreeCamera.prototype, "checkCollisions", void 0);
  17849. __decorate([
  17850. BABYLON.serialize()
  17851. ], FreeCamera.prototype, "applyGravity", void 0);
  17852. BABYLON.FreeCamera = FreeCamera;
  17853. })(BABYLON || (BABYLON = {}));
  17854. //# sourceMappingURL=babylon.freeCamera.js.map
  17855. var BABYLON;
  17856. (function (BABYLON) {
  17857. var FreeCameraInputsManager = (function (_super) {
  17858. __extends(FreeCameraInputsManager, _super);
  17859. function FreeCameraInputsManager(camera) {
  17860. return _super.call(this, camera) || this;
  17861. }
  17862. FreeCameraInputsManager.prototype.addKeyboard = function () {
  17863. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  17864. return this;
  17865. };
  17866. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  17867. if (touchEnabled === void 0) { touchEnabled = true; }
  17868. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  17869. return this;
  17870. };
  17871. FreeCameraInputsManager.prototype.addGamepad = function () {
  17872. this.add(new BABYLON.FreeCameraGamepadInput());
  17873. return this;
  17874. };
  17875. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  17876. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  17877. return this;
  17878. };
  17879. FreeCameraInputsManager.prototype.addTouch = function () {
  17880. this.add(new BABYLON.FreeCameraTouchInput());
  17881. return this;
  17882. };
  17883. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  17884. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  17885. return this;
  17886. };
  17887. return FreeCameraInputsManager;
  17888. }(BABYLON.CameraInputsManager));
  17889. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  17890. })(BABYLON || (BABYLON = {}));
  17891. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  17892. /// <reference path="babylon.targetCamera.ts" />
  17893. var BABYLON;
  17894. (function (BABYLON) {
  17895. var FollowCamera = (function (_super) {
  17896. __extends(FollowCamera, _super);
  17897. function FollowCamera(name, position, scene, lockedTarget) {
  17898. var _this = _super.call(this, name, position, scene) || this;
  17899. _this.radius = 12;
  17900. _this.rotationOffset = 0;
  17901. _this.heightOffset = 4;
  17902. _this.cameraAcceleration = 0.05;
  17903. _this.maxCameraSpeed = 20;
  17904. _this.lockedTarget = lockedTarget;
  17905. return _this;
  17906. }
  17907. FollowCamera.prototype.getRadians = function (degrees) {
  17908. return degrees * Math.PI / 180;
  17909. };
  17910. FollowCamera.prototype.follow = function (cameraTarget) {
  17911. if (!cameraTarget)
  17912. return;
  17913. var yRotation;
  17914. if (cameraTarget.rotationQuaternion) {
  17915. var rotMatrix = new BABYLON.Matrix();
  17916. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  17917. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  17918. }
  17919. else {
  17920. yRotation = cameraTarget.rotation.y;
  17921. }
  17922. var radians = this.getRadians(this.rotationOffset) + yRotation;
  17923. var targetPosition = cameraTarget.getAbsolutePosition();
  17924. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  17925. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  17926. var dx = targetX - this.position.x;
  17927. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  17928. var dz = (targetZ) - this.position.z;
  17929. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  17930. var vy = dy * this.cameraAcceleration;
  17931. var vz = dz * this.cameraAcceleration * 2;
  17932. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  17933. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17934. }
  17935. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  17936. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17937. }
  17938. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  17939. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  17940. }
  17941. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  17942. this.setTarget(targetPosition);
  17943. };
  17944. FollowCamera.prototype._checkInputs = function () {
  17945. _super.prototype._checkInputs.call(this);
  17946. this.follow(this.lockedTarget);
  17947. };
  17948. FollowCamera.prototype.getClassName = function () {
  17949. return "FollowCamera";
  17950. };
  17951. return FollowCamera;
  17952. }(BABYLON.TargetCamera));
  17953. __decorate([
  17954. BABYLON.serialize()
  17955. ], FollowCamera.prototype, "radius", void 0);
  17956. __decorate([
  17957. BABYLON.serialize()
  17958. ], FollowCamera.prototype, "rotationOffset", void 0);
  17959. __decorate([
  17960. BABYLON.serialize()
  17961. ], FollowCamera.prototype, "heightOffset", void 0);
  17962. __decorate([
  17963. BABYLON.serialize()
  17964. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  17965. __decorate([
  17966. BABYLON.serialize()
  17967. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  17968. __decorate([
  17969. BABYLON.serializeAsMeshReference("lockedTargetId")
  17970. ], FollowCamera.prototype, "lockedTarget", void 0);
  17971. BABYLON.FollowCamera = FollowCamera;
  17972. var ArcFollowCamera = (function (_super) {
  17973. __extends(ArcFollowCamera, _super);
  17974. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  17975. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  17976. _this.alpha = alpha;
  17977. _this.beta = beta;
  17978. _this.radius = radius;
  17979. _this.target = target;
  17980. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  17981. _this.follow();
  17982. return _this;
  17983. }
  17984. ArcFollowCamera.prototype.follow = function () {
  17985. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  17986. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  17987. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  17988. var targetPosition = this.target.getAbsolutePosition();
  17989. this.position = targetPosition.add(this._cartesianCoordinates);
  17990. this.setTarget(targetPosition);
  17991. };
  17992. ArcFollowCamera.prototype._checkInputs = function () {
  17993. _super.prototype._checkInputs.call(this);
  17994. this.follow();
  17995. };
  17996. ArcFollowCamera.prototype.getClassName = function () {
  17997. return "ArcFollowCamera";
  17998. };
  17999. return ArcFollowCamera;
  18000. }(BABYLON.TargetCamera));
  18001. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18002. })(BABYLON || (BABYLON = {}));
  18003. //# sourceMappingURL=babylon.followCamera.js.map
  18004. /// <reference path="babylon.freeCamera.ts" />
  18005. var BABYLON;
  18006. (function (BABYLON) {
  18007. // We're mainly based on the logic defined into the FreeCamera code
  18008. var TouchCamera = (function (_super) {
  18009. __extends(TouchCamera, _super);
  18010. //-- end properties for backward compatibility for inputs
  18011. function TouchCamera(name, position, scene) {
  18012. var _this = _super.call(this, name, position, scene) || this;
  18013. _this.inputs.addTouch();
  18014. _this._setupInputs();
  18015. return _this;
  18016. }
  18017. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18018. //-- Begin properties for backward compatibility for inputs
  18019. get: function () {
  18020. var touch = this.inputs.attached["touch"];
  18021. if (touch)
  18022. return touch.touchAngularSensibility;
  18023. },
  18024. set: function (value) {
  18025. var touch = this.inputs.attached["touch"];
  18026. if (touch)
  18027. touch.touchAngularSensibility = value;
  18028. },
  18029. enumerable: true,
  18030. configurable: true
  18031. });
  18032. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18033. get: function () {
  18034. var touch = this.inputs.attached["touch"];
  18035. if (touch)
  18036. return touch.touchMoveSensibility;
  18037. },
  18038. set: function (value) {
  18039. var touch = this.inputs.attached["touch"];
  18040. if (touch)
  18041. touch.touchMoveSensibility = value;
  18042. },
  18043. enumerable: true,
  18044. configurable: true
  18045. });
  18046. TouchCamera.prototype.getClassName = function () {
  18047. return "TouchCamera";
  18048. };
  18049. TouchCamera.prototype._setupInputs = function () {
  18050. var mouse = this.inputs.attached["mouse"];
  18051. if (mouse) {
  18052. mouse.touchEnabled = false;
  18053. }
  18054. };
  18055. return TouchCamera;
  18056. }(BABYLON.FreeCamera));
  18057. BABYLON.TouchCamera = TouchCamera;
  18058. })(BABYLON || (BABYLON = {}));
  18059. //# sourceMappingURL=babylon.touchCamera.js.map
  18060. /// <reference path="babylon.targetCamera.ts" />
  18061. /// <reference path="..\Tools\babylon.tools.ts" />
  18062. var BABYLON;
  18063. (function (BABYLON) {
  18064. var ArcRotateCamera = (function (_super) {
  18065. __extends(ArcRotateCamera, _super);
  18066. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18067. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18068. _this.inertialAlphaOffset = 0;
  18069. _this.inertialBetaOffset = 0;
  18070. _this.inertialRadiusOffset = 0;
  18071. _this.lowerAlphaLimit = null;
  18072. _this.upperAlphaLimit = null;
  18073. _this.lowerBetaLimit = 0.01;
  18074. _this.upperBetaLimit = Math.PI;
  18075. _this.lowerRadiusLimit = null;
  18076. _this.upperRadiusLimit = null;
  18077. _this.inertialPanningX = 0;
  18078. _this.inertialPanningY = 0;
  18079. //-- end properties for backward compatibility for inputs
  18080. _this.zoomOnFactor = 1;
  18081. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18082. _this.allowUpsideDown = true;
  18083. _this._viewMatrix = new BABYLON.Matrix();
  18084. // Panning
  18085. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18086. _this.checkCollisions = false;
  18087. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18088. _this._collider = new BABYLON.Collider();
  18089. _this._previousPosition = BABYLON.Vector3.Zero();
  18090. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18091. _this._newPosition = BABYLON.Vector3.Zero();
  18092. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18093. if (collidedMesh === void 0) { collidedMesh = null; }
  18094. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18095. newPosition.multiplyInPlace(_this._collider.radius);
  18096. }
  18097. if (!collidedMesh) {
  18098. _this._previousPosition.copyFrom(_this.position);
  18099. }
  18100. else {
  18101. _this.setPosition(newPosition);
  18102. if (_this.onCollide) {
  18103. _this.onCollide(collidedMesh);
  18104. }
  18105. }
  18106. // Recompute because of constraints
  18107. var cosa = Math.cos(_this.alpha);
  18108. var sina = Math.sin(_this.alpha);
  18109. var cosb = Math.cos(_this.beta);
  18110. var sinb = Math.sin(_this.beta);
  18111. if (sinb === 0) {
  18112. sinb = 0.0001;
  18113. }
  18114. var target = _this._getTargetPosition();
  18115. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18116. _this.position.copyFrom(_this._newPosition);
  18117. var up = _this.upVector;
  18118. if (_this.allowUpsideDown && _this.beta < 0) {
  18119. up = up.clone();
  18120. up = up.negate();
  18121. }
  18122. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18123. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18124. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18125. _this._collisionTriggered = false;
  18126. };
  18127. if (!target) {
  18128. _this.target = BABYLON.Vector3.Zero();
  18129. }
  18130. else {
  18131. _this.target = target;
  18132. }
  18133. _this.alpha = alpha;
  18134. _this.beta = beta;
  18135. _this.radius = radius;
  18136. _this.getViewMatrix();
  18137. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18138. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18139. return _this;
  18140. }
  18141. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18142. //-- begin properties for backward compatibility for inputs
  18143. get: function () {
  18144. var pointers = this.inputs.attached["pointers"];
  18145. if (pointers)
  18146. return pointers.angularSensibilityX;
  18147. },
  18148. set: function (value) {
  18149. var pointers = this.inputs.attached["pointers"];
  18150. if (pointers) {
  18151. pointers.angularSensibilityX = value;
  18152. }
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18158. get: function () {
  18159. var pointers = this.inputs.attached["pointers"];
  18160. if (pointers)
  18161. return pointers.angularSensibilityY;
  18162. },
  18163. set: function (value) {
  18164. var pointers = this.inputs.attached["pointers"];
  18165. if (pointers) {
  18166. pointers.angularSensibilityY = value;
  18167. }
  18168. },
  18169. enumerable: true,
  18170. configurable: true
  18171. });
  18172. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18173. get: function () {
  18174. var pointers = this.inputs.attached["pointers"];
  18175. if (pointers)
  18176. return pointers.pinchPrecision;
  18177. },
  18178. set: function (value) {
  18179. var pointers = this.inputs.attached["pointers"];
  18180. if (pointers) {
  18181. pointers.pinchPrecision = value;
  18182. }
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18188. get: function () {
  18189. var pointers = this.inputs.attached["pointers"];
  18190. if (pointers)
  18191. return pointers.panningSensibility;
  18192. },
  18193. set: function (value) {
  18194. var pointers = this.inputs.attached["pointers"];
  18195. if (pointers) {
  18196. pointers.panningSensibility = value;
  18197. }
  18198. },
  18199. enumerable: true,
  18200. configurable: true
  18201. });
  18202. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18203. get: function () {
  18204. var keyboard = this.inputs.attached["keyboard"];
  18205. if (keyboard)
  18206. return keyboard.keysUp;
  18207. },
  18208. set: function (value) {
  18209. var keyboard = this.inputs.attached["keyboard"];
  18210. if (keyboard)
  18211. keyboard.keysUp = value;
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18217. get: function () {
  18218. var keyboard = this.inputs.attached["keyboard"];
  18219. if (keyboard)
  18220. return keyboard.keysDown;
  18221. },
  18222. set: function (value) {
  18223. var keyboard = this.inputs.attached["keyboard"];
  18224. if (keyboard)
  18225. keyboard.keysDown = value;
  18226. },
  18227. enumerable: true,
  18228. configurable: true
  18229. });
  18230. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18231. get: function () {
  18232. var keyboard = this.inputs.attached["keyboard"];
  18233. if (keyboard)
  18234. return keyboard.keysLeft;
  18235. },
  18236. set: function (value) {
  18237. var keyboard = this.inputs.attached["keyboard"];
  18238. if (keyboard)
  18239. keyboard.keysLeft = value;
  18240. },
  18241. enumerable: true,
  18242. configurable: true
  18243. });
  18244. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18245. get: function () {
  18246. var keyboard = this.inputs.attached["keyboard"];
  18247. if (keyboard)
  18248. return keyboard.keysRight;
  18249. },
  18250. set: function (value) {
  18251. var keyboard = this.inputs.attached["keyboard"];
  18252. if (keyboard)
  18253. keyboard.keysRight = value;
  18254. },
  18255. enumerable: true,
  18256. configurable: true
  18257. });
  18258. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18259. get: function () {
  18260. var mousewheel = this.inputs.attached["mousewheel"];
  18261. if (mousewheel)
  18262. return mousewheel.wheelPrecision;
  18263. },
  18264. set: function (value) {
  18265. var mousewheel = this.inputs.attached["mousewheel"];
  18266. if (mousewheel)
  18267. mousewheel.wheelPrecision = value;
  18268. },
  18269. enumerable: true,
  18270. configurable: true
  18271. });
  18272. // Cache
  18273. ArcRotateCamera.prototype._initCache = function () {
  18274. _super.prototype._initCache.call(this);
  18275. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18276. this._cache.alpha = undefined;
  18277. this._cache.beta = undefined;
  18278. this._cache.radius = undefined;
  18279. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18280. };
  18281. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18282. if (!ignoreParentClass) {
  18283. _super.prototype._updateCache.call(this);
  18284. }
  18285. this._cache.target.copyFrom(this._getTargetPosition());
  18286. this._cache.alpha = this.alpha;
  18287. this._cache.beta = this.beta;
  18288. this._cache.radius = this.radius;
  18289. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18290. };
  18291. ArcRotateCamera.prototype._getTargetPosition = function () {
  18292. if (this.target.getAbsolutePosition) {
  18293. var pos = this.target.getAbsolutePosition();
  18294. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18295. }
  18296. return this.target;
  18297. };
  18298. // Synchronized
  18299. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18300. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18301. return false;
  18302. return this._cache.target.equals(this.target)
  18303. && this._cache.alpha === this.alpha
  18304. && this._cache.beta === this.beta
  18305. && this._cache.radius === this.radius
  18306. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18307. };
  18308. // Methods
  18309. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18310. var _this = this;
  18311. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18312. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18313. this._useCtrlForPanning = useCtrlForPanning;
  18314. this._panningMouseButton = panningMouseButton;
  18315. this.inputs.attachElement(element, noPreventDefault);
  18316. this._reset = function () {
  18317. _this.inertialAlphaOffset = 0;
  18318. _this.inertialBetaOffset = 0;
  18319. _this.inertialRadiusOffset = 0;
  18320. };
  18321. };
  18322. ArcRotateCamera.prototype.detachControl = function (element) {
  18323. this.inputs.detachElement(element);
  18324. if (this._reset) {
  18325. this._reset();
  18326. }
  18327. };
  18328. ArcRotateCamera.prototype._checkInputs = function () {
  18329. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18330. if (this._collisionTriggered) {
  18331. return;
  18332. }
  18333. this.inputs.checkInputs();
  18334. // Inertia
  18335. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18336. if (this.getScene().useRightHandedSystem) {
  18337. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18338. }
  18339. else {
  18340. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18341. }
  18342. this.beta += this.inertialBetaOffset;
  18343. this.radius -= this.inertialRadiusOffset;
  18344. this.inertialAlphaOffset *= this.inertia;
  18345. this.inertialBetaOffset *= this.inertia;
  18346. this.inertialRadiusOffset *= this.inertia;
  18347. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18348. this.inertialAlphaOffset = 0;
  18349. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18350. this.inertialBetaOffset = 0;
  18351. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18352. this.inertialRadiusOffset = 0;
  18353. }
  18354. // Panning inertia
  18355. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18356. if (!this._localDirection) {
  18357. this._localDirection = BABYLON.Vector3.Zero();
  18358. this._transformedDirection = BABYLON.Vector3.Zero();
  18359. }
  18360. this.inertialPanningX *= this.inertia;
  18361. this.inertialPanningY *= this.inertia;
  18362. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18363. this.inertialPanningX = 0;
  18364. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18365. this.inertialPanningY = 0;
  18366. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18367. this._localDirection.multiplyInPlace(this.panningAxis);
  18368. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18369. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18370. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18371. if (!this.panningAxis.y) {
  18372. this._transformedDirection.y = 0;
  18373. }
  18374. if (!this.target.getAbsolutePosition) {
  18375. this.target.addInPlace(this._transformedDirection);
  18376. }
  18377. }
  18378. // Limits
  18379. this._checkLimits();
  18380. _super.prototype._checkInputs.call(this);
  18381. };
  18382. ArcRotateCamera.prototype._checkLimits = function () {
  18383. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18384. if (this.allowUpsideDown && this.beta > Math.PI) {
  18385. this.beta = this.beta - (2 * Math.PI);
  18386. }
  18387. }
  18388. else {
  18389. if (this.beta < this.lowerBetaLimit) {
  18390. this.beta = this.lowerBetaLimit;
  18391. }
  18392. }
  18393. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18394. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18395. this.beta = this.beta + (2 * Math.PI);
  18396. }
  18397. }
  18398. else {
  18399. if (this.beta > this.upperBetaLimit) {
  18400. this.beta = this.upperBetaLimit;
  18401. }
  18402. }
  18403. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18404. this.alpha = this.lowerAlphaLimit;
  18405. }
  18406. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18407. this.alpha = this.upperAlphaLimit;
  18408. }
  18409. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18410. this.radius = this.lowerRadiusLimit;
  18411. }
  18412. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18413. this.radius = this.upperRadiusLimit;
  18414. }
  18415. };
  18416. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18417. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18418. this.radius = radiusv3.length();
  18419. // Alpha
  18420. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18421. if (radiusv3.z < 0) {
  18422. this.alpha = 2 * Math.PI - this.alpha;
  18423. }
  18424. // Beta
  18425. this.beta = Math.acos(radiusv3.y / this.radius);
  18426. this._checkLimits();
  18427. };
  18428. ArcRotateCamera.prototype.setPosition = function (position) {
  18429. if (this.position.equals(position)) {
  18430. return;
  18431. }
  18432. this.position.copyFrom(position);
  18433. this.rebuildAnglesAndRadius();
  18434. };
  18435. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18436. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18437. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18438. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18439. return;
  18440. }
  18441. if (toBoundingCenter && target.getBoundingInfo) {
  18442. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  18443. }
  18444. else {
  18445. this._targetBoundingCenter = null;
  18446. }
  18447. this.target = target;
  18448. this.rebuildAnglesAndRadius();
  18449. };
  18450. ArcRotateCamera.prototype._getViewMatrix = function () {
  18451. // Compute
  18452. var cosa = Math.cos(this.alpha);
  18453. var sina = Math.sin(this.alpha);
  18454. var cosb = Math.cos(this.beta);
  18455. var sinb = Math.sin(this.beta);
  18456. if (sinb === 0) {
  18457. sinb = 0.0001;
  18458. }
  18459. var target = this._getTargetPosition();
  18460. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18461. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18462. this._collider.radius = this.collisionRadius;
  18463. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18464. this._collisionTriggered = true;
  18465. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18466. }
  18467. else {
  18468. this.position.copyFrom(this._newPosition);
  18469. var up = this.upVector;
  18470. if (this.allowUpsideDown && sinb < 0) {
  18471. up = up.clone();
  18472. up = up.negate();
  18473. }
  18474. if (this.getScene().useRightHandedSystem) {
  18475. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18476. }
  18477. else {
  18478. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18479. }
  18480. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18481. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18482. }
  18483. this._currentTarget = target;
  18484. return this._viewMatrix;
  18485. };
  18486. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18487. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18488. meshes = meshes || this.getScene().meshes;
  18489. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18490. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18491. this.radius = distance * this.zoomOnFactor;
  18492. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18493. };
  18494. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18495. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18496. var meshesOrMinMaxVector;
  18497. var distance;
  18498. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18499. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18500. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18501. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18502. }
  18503. else {
  18504. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18505. distance = meshesOrMinMaxVectorAndDistance.distance;
  18506. }
  18507. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18508. if (!doNotUpdateMaxZ) {
  18509. this.maxZ = distance * 2;
  18510. }
  18511. };
  18512. /**
  18513. * @override
  18514. * Override Camera.createRigCamera
  18515. */
  18516. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18517. var alphaShift;
  18518. switch (this.cameraRigMode) {
  18519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18520. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18521. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18522. case BABYLON.Camera.RIG_MODE_VR:
  18523. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18524. break;
  18525. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18526. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18527. break;
  18528. }
  18529. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18530. rigCam._cameraRigParams = {};
  18531. return rigCam;
  18532. };
  18533. /**
  18534. * @override
  18535. * Override Camera._updateRigCameras
  18536. */
  18537. ArcRotateCamera.prototype._updateRigCameras = function () {
  18538. var camLeft = this._rigCameras[0];
  18539. var camRight = this._rigCameras[1];
  18540. camLeft.beta = camRight.beta = this.beta;
  18541. camLeft.radius = camRight.radius = this.radius;
  18542. switch (this.cameraRigMode) {
  18543. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18544. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18545. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18546. case BABYLON.Camera.RIG_MODE_VR:
  18547. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18548. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18549. break;
  18550. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18551. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18552. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18553. break;
  18554. }
  18555. _super.prototype._updateRigCameras.call(this);
  18556. };
  18557. ArcRotateCamera.prototype.dispose = function () {
  18558. this.inputs.clear();
  18559. _super.prototype.dispose.call(this);
  18560. };
  18561. ArcRotateCamera.prototype.getClassName = function () {
  18562. return "ArcRotateCamera";
  18563. };
  18564. return ArcRotateCamera;
  18565. }(BABYLON.TargetCamera));
  18566. __decorate([
  18567. BABYLON.serialize()
  18568. ], ArcRotateCamera.prototype, "alpha", void 0);
  18569. __decorate([
  18570. BABYLON.serialize()
  18571. ], ArcRotateCamera.prototype, "beta", void 0);
  18572. __decorate([
  18573. BABYLON.serialize()
  18574. ], ArcRotateCamera.prototype, "radius", void 0);
  18575. __decorate([
  18576. BABYLON.serializeAsVector3()
  18577. ], ArcRotateCamera.prototype, "target", void 0);
  18578. __decorate([
  18579. BABYLON.serialize()
  18580. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18581. __decorate([
  18582. BABYLON.serialize()
  18583. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18584. __decorate([
  18585. BABYLON.serialize()
  18586. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18587. __decorate([
  18588. BABYLON.serialize()
  18589. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18590. __decorate([
  18591. BABYLON.serialize()
  18592. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18593. __decorate([
  18594. BABYLON.serialize()
  18595. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18596. __decorate([
  18597. BABYLON.serialize()
  18598. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18599. __decorate([
  18600. BABYLON.serialize()
  18601. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18602. __decorate([
  18603. BABYLON.serialize()
  18604. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18605. __decorate([
  18606. BABYLON.serialize()
  18607. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18608. __decorate([
  18609. BABYLON.serialize()
  18610. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18611. __decorate([
  18612. BABYLON.serialize()
  18613. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18614. __decorate([
  18615. BABYLON.serialize()
  18616. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18617. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18618. })(BABYLON || (BABYLON = {}));
  18619. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18620. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18621. var BABYLON;
  18622. (function (BABYLON) {
  18623. var ArcRotateCameraInputsManager = (function (_super) {
  18624. __extends(ArcRotateCameraInputsManager, _super);
  18625. function ArcRotateCameraInputsManager(camera) {
  18626. return _super.call(this, camera) || this;
  18627. }
  18628. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18629. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18630. return this;
  18631. };
  18632. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18633. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18634. return this;
  18635. };
  18636. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18637. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18638. return this;
  18639. };
  18640. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18641. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18642. return this;
  18643. };
  18644. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18645. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18646. return this;
  18647. };
  18648. return ArcRotateCameraInputsManager;
  18649. }(BABYLON.CameraInputsManager));
  18650. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18651. })(BABYLON || (BABYLON = {}));
  18652. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18653. var BABYLON;
  18654. (function (BABYLON) {
  18655. var RenderingManager = (function () {
  18656. function RenderingManager(scene) {
  18657. this._renderingGroups = new Array();
  18658. this._autoClearDepthStencil = {};
  18659. this._customOpaqueSortCompareFn = {};
  18660. this._customAlphaTestSortCompareFn = {};
  18661. this._customTransparentSortCompareFn = {};
  18662. this._renderinGroupInfo = null;
  18663. this._scene = scene;
  18664. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18665. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18666. }
  18667. }
  18668. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18669. if (depth === void 0) { depth = true; }
  18670. if (stencil === void 0) { stencil = true; }
  18671. if (this._depthStencilBufferAlreadyCleaned) {
  18672. return;
  18673. }
  18674. this._scene.getEngine().clear(null, false, depth, stencil);
  18675. this._depthStencilBufferAlreadyCleaned = true;
  18676. };
  18677. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18678. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18679. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18680. var info = null;
  18681. if (observable) {
  18682. if (!this._renderinGroupInfo) {
  18683. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18684. }
  18685. info = this._renderinGroupInfo;
  18686. info.scene = this._scene;
  18687. info.camera = this._scene.activeCamera;
  18688. }
  18689. // Dispatch sprites
  18690. if (renderSprites) {
  18691. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18692. var manager = this._scene.spriteManagers[index];
  18693. this.dispatchSprites(manager);
  18694. }
  18695. }
  18696. // Render
  18697. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18698. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18699. var renderingGroup = this._renderingGroups[index];
  18700. if (!renderingGroup && !observable)
  18701. continue;
  18702. this._currentIndex = index;
  18703. var renderingGroupMask = 0;
  18704. // Fire PRECLEAR stage
  18705. if (observable) {
  18706. renderingGroupMask = Math.pow(2, index);
  18707. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18708. info.renderingGroupId = index;
  18709. observable.notifyObservers(info, renderingGroupMask);
  18710. }
  18711. // Clear depth/stencil if needed
  18712. var autoClear = this._autoClearDepthStencil[index];
  18713. if (autoClear && autoClear.autoClear) {
  18714. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18715. }
  18716. if (observable) {
  18717. // Fire PREOPAQUE stage
  18718. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18719. observable.notifyObservers(info, renderingGroupMask);
  18720. // Fire PRETRANSPARENT stage
  18721. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18722. observable.notifyObservers(info, renderingGroupMask);
  18723. }
  18724. if (renderingGroup)
  18725. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18726. // Fire POSTTRANSPARENT stage
  18727. if (observable) {
  18728. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18729. observable.notifyObservers(info, renderingGroupMask);
  18730. }
  18731. }
  18732. };
  18733. RenderingManager.prototype.reset = function () {
  18734. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18735. var renderingGroup = this._renderingGroups[index];
  18736. if (renderingGroup) {
  18737. renderingGroup.prepare();
  18738. }
  18739. }
  18740. };
  18741. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18742. if (!this._renderingGroups[renderingGroupId]) {
  18743. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18744. }
  18745. };
  18746. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18747. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18748. this._prepareRenderingGroup(renderingGroupId);
  18749. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18750. };
  18751. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18752. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18753. this._prepareRenderingGroup(renderingGroupId);
  18754. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18755. };
  18756. RenderingManager.prototype.dispatch = function (subMesh) {
  18757. var mesh = subMesh.getMesh();
  18758. var renderingGroupId = mesh.renderingGroupId || 0;
  18759. this._prepareRenderingGroup(renderingGroupId);
  18760. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18761. };
  18762. /**
  18763. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18764. * This allowed control for front to back rendering or reversly depending of the special needs.
  18765. *
  18766. * @param renderingGroupId The rendering group id corresponding to its index
  18767. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18768. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18769. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18770. */
  18771. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18772. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18773. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18774. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18775. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18776. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18777. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18778. if (this._renderingGroups[renderingGroupId]) {
  18779. var group = this._renderingGroups[renderingGroupId];
  18780. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18781. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18782. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18783. }
  18784. };
  18785. /**
  18786. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18787. *
  18788. * @param renderingGroupId The rendering group id corresponding to its index
  18789. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18790. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18791. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18792. */
  18793. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18794. if (depth === void 0) { depth = true; }
  18795. if (stencil === void 0) { stencil = true; }
  18796. this._autoClearDepthStencil[renderingGroupId] = {
  18797. autoClear: autoClearDepthStencil,
  18798. depth: depth,
  18799. stencil: stencil
  18800. };
  18801. };
  18802. return RenderingManager;
  18803. }());
  18804. /**
  18805. * The max id used for rendering groups (not included)
  18806. */
  18807. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18808. /**
  18809. * The min id used for rendering groups (included)
  18810. */
  18811. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18812. BABYLON.RenderingManager = RenderingManager;
  18813. })(BABYLON || (BABYLON = {}));
  18814. //# sourceMappingURL=babylon.renderingManager.js.map
  18815. var BABYLON;
  18816. (function (BABYLON) {
  18817. var RenderingGroup = (function () {
  18818. /**
  18819. * Creates a new rendering group.
  18820. * @param index The rendering group index
  18821. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18822. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18823. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18824. */
  18825. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18826. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18827. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18828. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18829. this.index = index;
  18830. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18831. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18832. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18833. this._particleSystems = new BABYLON.SmartArray(256);
  18834. this._spriteManagers = new BABYLON.SmartArray(256);
  18835. this._scene = scene;
  18836. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18837. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18838. this.transparentSortCompareFn = transparentSortCompareFn;
  18839. }
  18840. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18841. /**
  18842. * Set the opaque sort comparison function.
  18843. * If null the sub meshes will be render in the order they were created
  18844. */
  18845. set: function (value) {
  18846. this._opaqueSortCompareFn = value;
  18847. if (value) {
  18848. this._renderOpaque = this.renderOpaqueSorted;
  18849. }
  18850. else {
  18851. this._renderOpaque = RenderingGroup.renderUnsorted;
  18852. }
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18858. /**
  18859. * Set the alpha test sort comparison function.
  18860. * If null the sub meshes will be render in the order they were created
  18861. */
  18862. set: function (value) {
  18863. this._alphaTestSortCompareFn = value;
  18864. if (value) {
  18865. this._renderAlphaTest = this.renderAlphaTestSorted;
  18866. }
  18867. else {
  18868. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18869. }
  18870. },
  18871. enumerable: true,
  18872. configurable: true
  18873. });
  18874. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18875. /**
  18876. * Set the transparent sort comparison function.
  18877. * If null the sub meshes will be render in the order they were created
  18878. */
  18879. set: function (value) {
  18880. if (value) {
  18881. this._transparentSortCompareFn = value;
  18882. }
  18883. else {
  18884. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18885. }
  18886. this._renderTransparent = this.renderTransparentSorted;
  18887. },
  18888. enumerable: true,
  18889. configurable: true
  18890. });
  18891. /**
  18892. * Render all the sub meshes contained in the group.
  18893. * @param customRenderFunction Used to override the default render behaviour of the group.
  18894. * @returns true if rendered some submeshes.
  18895. */
  18896. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18897. if (customRenderFunction) {
  18898. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  18899. return;
  18900. }
  18901. var engine = this._scene.getEngine();
  18902. // Opaque
  18903. if (this._opaqueSubMeshes.length !== 0) {
  18904. this._renderOpaque(this._opaqueSubMeshes);
  18905. }
  18906. // Alpha test
  18907. if (this._alphaTestSubMeshes.length !== 0) {
  18908. engine.setAlphaTesting(true);
  18909. this._renderAlphaTest(this._alphaTestSubMeshes);
  18910. engine.setAlphaTesting(false);
  18911. }
  18912. // Sprites
  18913. if (renderSprites) {
  18914. this._renderSprites();
  18915. }
  18916. // Particles
  18917. if (renderParticles) {
  18918. this._renderParticles(activeMeshes);
  18919. }
  18920. if (this.onBeforeTransparentRendering) {
  18921. this.onBeforeTransparentRendering();
  18922. }
  18923. // Transparent
  18924. if (this._transparentSubMeshes.length !== 0) {
  18925. this._renderTransparent(this._transparentSubMeshes);
  18926. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18927. }
  18928. };
  18929. /**
  18930. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18931. * @param subMeshes The submeshes to render
  18932. */
  18933. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18934. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18935. };
  18936. /**
  18937. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18938. * @param subMeshes The submeshes to render
  18939. */
  18940. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18941. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  18942. };
  18943. /**
  18944. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18945. * @param subMeshes The submeshes to render
  18946. */
  18947. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18948. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  18949. };
  18950. /**
  18951. * Renders the submeshes in a specified order.
  18952. * @param subMeshes The submeshes to sort before render
  18953. * @param sortCompareFn The comparison function use to sort
  18954. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18955. * @param transparent Specifies to activate blending if true
  18956. */
  18957. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  18958. var subIndex = 0;
  18959. var subMesh;
  18960. for (; subIndex < subMeshes.length; subIndex++) {
  18961. subMesh = subMeshes.data[subIndex];
  18962. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18963. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18964. }
  18965. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18966. sortedArray.sort(sortCompareFn);
  18967. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18968. subMesh = sortedArray[subIndex];
  18969. subMesh.render(transparent);
  18970. }
  18971. };
  18972. /**
  18973. * Renders the submeshes in the order they were dispatched (no sort applied).
  18974. * @param subMeshes The submeshes to render
  18975. */
  18976. RenderingGroup.renderUnsorted = function (subMeshes) {
  18977. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18978. var submesh = subMeshes.data[subIndex];
  18979. submesh.render(false);
  18980. }
  18981. };
  18982. /**
  18983. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18984. * are rendered back to front if in the same alpha index.
  18985. *
  18986. * @param a The first submesh
  18987. * @param b The second submesh
  18988. * @returns The result of the comparison
  18989. */
  18990. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18991. // Alpha index first
  18992. if (a._alphaIndex > b._alphaIndex) {
  18993. return 1;
  18994. }
  18995. if (a._alphaIndex < b._alphaIndex) {
  18996. return -1;
  18997. }
  18998. // Then distance to camera
  18999. return RenderingGroup.backToFrontSortCompare(a, b);
  19000. };
  19001. /**
  19002. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19003. * are rendered back to front.
  19004. *
  19005. * @param a The first submesh
  19006. * @param b The second submesh
  19007. * @returns The result of the comparison
  19008. */
  19009. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19010. // Then distance to camera
  19011. if (a._distanceToCamera < b._distanceToCamera) {
  19012. return 1;
  19013. }
  19014. if (a._distanceToCamera > b._distanceToCamera) {
  19015. return -1;
  19016. }
  19017. return 0;
  19018. };
  19019. /**
  19020. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19021. * are rendered front to back (prevent overdraw).
  19022. *
  19023. * @param a The first submesh
  19024. * @param b The second submesh
  19025. * @returns The result of the comparison
  19026. */
  19027. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19028. // Then distance to camera
  19029. if (a._distanceToCamera < b._distanceToCamera) {
  19030. return -1;
  19031. }
  19032. if (a._distanceToCamera > b._distanceToCamera) {
  19033. return 1;
  19034. }
  19035. return 0;
  19036. };
  19037. /**
  19038. * Resets the different lists of submeshes to prepare a new frame.
  19039. */
  19040. RenderingGroup.prototype.prepare = function () {
  19041. this._opaqueSubMeshes.reset();
  19042. this._transparentSubMeshes.reset();
  19043. this._alphaTestSubMeshes.reset();
  19044. this._particleSystems.reset();
  19045. this._spriteManagers.reset();
  19046. };
  19047. /**
  19048. * Inserts the submesh in its correct queue depending on its material.
  19049. * @param subMesh The submesh to dispatch
  19050. */
  19051. RenderingGroup.prototype.dispatch = function (subMesh) {
  19052. var material = subMesh.getMaterial();
  19053. var mesh = subMesh.getMesh();
  19054. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19055. this._transparentSubMeshes.push(subMesh);
  19056. }
  19057. else if (material.needAlphaTesting()) {
  19058. this._alphaTestSubMeshes.push(subMesh);
  19059. }
  19060. else {
  19061. this._opaqueSubMeshes.push(subMesh); // Opaque
  19062. }
  19063. };
  19064. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19065. this._spriteManagers.push(spriteManager);
  19066. };
  19067. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19068. this._particleSystems.push(particleSystem);
  19069. };
  19070. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19071. if (this._particleSystems.length === 0) {
  19072. return;
  19073. }
  19074. // Particles
  19075. var activeCamera = this._scene.activeCamera;
  19076. this._scene._particlesDuration.beginMonitoring();
  19077. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19078. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19079. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19080. continue;
  19081. }
  19082. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19083. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19084. }
  19085. }
  19086. this._scene._particlesDuration.endMonitoring(false);
  19087. };
  19088. RenderingGroup.prototype._renderSprites = function () {
  19089. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19090. return;
  19091. }
  19092. // Sprites
  19093. var activeCamera = this._scene.activeCamera;
  19094. this._scene._spritesDuration.beginMonitoring();
  19095. for (var id = 0; id < this._spriteManagers.length; id++) {
  19096. var spriteManager = this._spriteManagers.data[id];
  19097. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19098. spriteManager.render();
  19099. }
  19100. }
  19101. this._scene._spritesDuration.endMonitoring(false);
  19102. };
  19103. return RenderingGroup;
  19104. }());
  19105. BABYLON.RenderingGroup = RenderingGroup;
  19106. })(BABYLON || (BABYLON = {}));
  19107. //# sourceMappingURL=babylon.renderingGroup.js.map
  19108. var BABYLON;
  19109. (function (BABYLON) {
  19110. var PointerEventTypes = (function () {
  19111. function PointerEventTypes() {
  19112. }
  19113. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19114. get: function () {
  19115. return PointerEventTypes._POINTERDOWN;
  19116. },
  19117. enumerable: true,
  19118. configurable: true
  19119. });
  19120. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19121. get: function () {
  19122. return PointerEventTypes._POINTERUP;
  19123. },
  19124. enumerable: true,
  19125. configurable: true
  19126. });
  19127. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19128. get: function () {
  19129. return PointerEventTypes._POINTERMOVE;
  19130. },
  19131. enumerable: true,
  19132. configurable: true
  19133. });
  19134. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19135. get: function () {
  19136. return PointerEventTypes._POINTERWHEEL;
  19137. },
  19138. enumerable: true,
  19139. configurable: true
  19140. });
  19141. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19142. get: function () {
  19143. return PointerEventTypes._POINTERPICK;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. return PointerEventTypes;
  19149. }());
  19150. PointerEventTypes._POINTERDOWN = 0x01;
  19151. PointerEventTypes._POINTERUP = 0x02;
  19152. PointerEventTypes._POINTERMOVE = 0x04;
  19153. PointerEventTypes._POINTERWHEEL = 0x08;
  19154. PointerEventTypes._POINTERPICK = 0x10;
  19155. BABYLON.PointerEventTypes = PointerEventTypes;
  19156. var PointerInfoBase = (function () {
  19157. function PointerInfoBase(type, event) {
  19158. this.type = type;
  19159. this.event = event;
  19160. }
  19161. return PointerInfoBase;
  19162. }());
  19163. BABYLON.PointerInfoBase = PointerInfoBase;
  19164. /**
  19165. * This class is used to store pointer related info for the onPrePointerObservable event.
  19166. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19167. */
  19168. var PointerInfoPre = (function (_super) {
  19169. __extends(PointerInfoPre, _super);
  19170. function PointerInfoPre(type, event, localX, localY) {
  19171. var _this = _super.call(this, type, event) || this;
  19172. _this.skipOnPointerObservable = false;
  19173. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19174. return _this;
  19175. }
  19176. return PointerInfoPre;
  19177. }(PointerInfoBase));
  19178. BABYLON.PointerInfoPre = PointerInfoPre;
  19179. /**
  19180. * This type contains all the data related to a pointer event in Babylon.js.
  19181. * 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.
  19182. */
  19183. var PointerInfo = (function (_super) {
  19184. __extends(PointerInfo, _super);
  19185. function PointerInfo(type, event, pickInfo) {
  19186. var _this = _super.call(this, type, event) || this;
  19187. _this.pickInfo = pickInfo;
  19188. return _this;
  19189. }
  19190. return PointerInfo;
  19191. }(PointerInfoBase));
  19192. BABYLON.PointerInfo = PointerInfo;
  19193. /**
  19194. * This class is used by the onRenderingGroupObservable
  19195. */
  19196. var RenderingGroupInfo = (function () {
  19197. function RenderingGroupInfo() {
  19198. }
  19199. return RenderingGroupInfo;
  19200. }());
  19201. /**
  19202. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19203. * This stage will be fired no matter what
  19204. */
  19205. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19206. /**
  19207. * Called before opaque object are rendered.
  19208. * This stage will be fired only if there's 3D Opaque content to render
  19209. */
  19210. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19211. /**
  19212. * Called after the opaque objects are rendered and before the transparent ones
  19213. * This stage will be fired only if there's 3D transparent content to render
  19214. */
  19215. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19216. /**
  19217. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19218. * This stage will be fired no matter what
  19219. */
  19220. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19221. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19222. /**
  19223. * Represents a scene to be rendered by the engine.
  19224. * @see http://doc.babylonjs.com/page.php?p=21911
  19225. */
  19226. var Scene = (function () {
  19227. /**
  19228. * @constructor
  19229. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19230. */
  19231. function Scene(engine) {
  19232. // Members
  19233. this.autoClear = true;
  19234. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19235. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19236. this.forceWireframe = false;
  19237. this.forcePointsCloud = false;
  19238. this.forceShowBoundingBoxes = false;
  19239. this.animationsEnabled = true;
  19240. this.constantlyUpdateMeshUnderPointer = false;
  19241. this.useRightHandedSystem = false;
  19242. this.hoverCursor = "pointer";
  19243. // Metadata
  19244. this.metadata = null;
  19245. // Events
  19246. /**
  19247. * An event triggered when the scene is disposed.
  19248. * @type {BABYLON.Observable}
  19249. */
  19250. this.onDisposeObservable = new BABYLON.Observable();
  19251. /**
  19252. * An event triggered before rendering the scene
  19253. * @type {BABYLON.Observable}
  19254. */
  19255. this.onBeforeRenderObservable = new BABYLON.Observable();
  19256. /**
  19257. * An event triggered after rendering the scene
  19258. * @type {BABYLON.Observable}
  19259. */
  19260. this.onAfterRenderObservable = new BABYLON.Observable();
  19261. /**
  19262. * An event triggered when the scene is ready
  19263. * @type {BABYLON.Observable}
  19264. */
  19265. this.onReadyObservable = new BABYLON.Observable();
  19266. /**
  19267. * An event triggered before rendering a camera
  19268. * @type {BABYLON.Observable}
  19269. */
  19270. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19271. /**
  19272. * An event triggered after rendering a camera
  19273. * @type {BABYLON.Observable}
  19274. */
  19275. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19276. /**
  19277. * An event triggered when a camera is created
  19278. * @type {BABYLON.Observable}
  19279. */
  19280. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19281. /**
  19282. * An event triggered when a camera is removed
  19283. * @type {BABYLON.Observable}
  19284. */
  19285. this.onCameraRemovedObservable = new BABYLON.Observable();
  19286. /**
  19287. * An event triggered when a light is created
  19288. * @type {BABYLON.Observable}
  19289. */
  19290. this.onNewLightAddedObservable = new BABYLON.Observable();
  19291. /**
  19292. * An event triggered when a light is removed
  19293. * @type {BABYLON.Observable}
  19294. */
  19295. this.onLightRemovedObservable = new BABYLON.Observable();
  19296. /**
  19297. * An event triggered when a geometry is created
  19298. * @type {BABYLON.Observable}
  19299. */
  19300. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19301. /**
  19302. * An event triggered when a geometry is removed
  19303. * @type {BABYLON.Observable}
  19304. */
  19305. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19306. /**
  19307. * An event triggered when a mesh is created
  19308. * @type {BABYLON.Observable}
  19309. */
  19310. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19311. /**
  19312. * An event triggered when a mesh is removed
  19313. * @type {BABYLON.Observable}
  19314. */
  19315. this.onMeshRemovedObservable = new BABYLON.Observable();
  19316. /**
  19317. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19318. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19319. * 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)
  19320. */
  19321. this.onRenderingGroupObservable = new BABYLON.Observable();
  19322. // Animations
  19323. this.animations = [];
  19324. /**
  19325. * 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).
  19326. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19327. */
  19328. this.onPrePointerObservable = new BABYLON.Observable();
  19329. /**
  19330. * Observable event triggered each time an input event is received from the rendering canvas
  19331. */
  19332. this.onPointerObservable = new BABYLON.Observable();
  19333. 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
  19334. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19335. this._startingPointerTime = 0;
  19336. // Fog
  19337. /**
  19338. * is fog enabled on this scene.
  19339. * @type {boolean}
  19340. */
  19341. this.fogEnabled = true;
  19342. this.fogMode = Scene.FOGMODE_NONE;
  19343. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19344. this.fogDensity = 0.1;
  19345. this.fogStart = 0;
  19346. this.fogEnd = 1000.0;
  19347. // Lights
  19348. /**
  19349. * is shadow enabled on this scene.
  19350. * @type {boolean}
  19351. */
  19352. this.shadowsEnabled = true;
  19353. /**
  19354. * is light enabled on this scene.
  19355. * @type {boolean}
  19356. */
  19357. this.lightsEnabled = true;
  19358. /**
  19359. * All of the lights added to this scene.
  19360. * @see BABYLON.Light
  19361. * @type {BABYLON.Light[]}
  19362. */
  19363. this.lights = new Array();
  19364. // Cameras
  19365. /**
  19366. * All of the cameras added to this scene.
  19367. * @see BABYLON.Camera
  19368. * @type {BABYLON.Camera[]}
  19369. */
  19370. this.cameras = new Array();
  19371. this.activeCameras = new Array();
  19372. // Meshes
  19373. /**
  19374. * All of the (abstract) meshes added to this scene.
  19375. * @see BABYLON.AbstractMesh
  19376. * @type {BABYLON.AbstractMesh[]}
  19377. */
  19378. this.meshes = new Array();
  19379. // Geometries
  19380. this._geometries = new Array();
  19381. this.materials = new Array();
  19382. this.multiMaterials = new Array();
  19383. // Textures
  19384. this.texturesEnabled = true;
  19385. this.textures = new Array();
  19386. // Particles
  19387. this.particlesEnabled = true;
  19388. this.particleSystems = new Array();
  19389. // Sprites
  19390. this.spritesEnabled = true;
  19391. this.spriteManagers = new Array();
  19392. // Layers
  19393. this.layers = new Array();
  19394. this.highlightLayers = new Array();
  19395. // Skeletons
  19396. this.skeletonsEnabled = true;
  19397. this.skeletons = new Array();
  19398. // Lens flares
  19399. this.lensFlaresEnabled = true;
  19400. this.lensFlareSystems = new Array();
  19401. // Collisions
  19402. this.collisionsEnabled = true;
  19403. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19404. // Postprocesses
  19405. this.postProcessesEnabled = true;
  19406. // Customs render targets
  19407. this.renderTargetsEnabled = true;
  19408. this.dumpNextRenderTargets = false;
  19409. this.customRenderTargets = new Array();
  19410. // Imported meshes
  19411. this.importedMeshesFiles = new Array();
  19412. // Probes
  19413. this.probesEnabled = true;
  19414. this.reflectionProbes = new Array();
  19415. this._actionManagers = new Array();
  19416. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19417. // Procedural textures
  19418. this.proceduralTexturesEnabled = true;
  19419. this._proceduralTextures = new Array();
  19420. this.soundTracks = new Array();
  19421. this._audioEnabled = true;
  19422. this._headphone = false;
  19423. // Performance counters
  19424. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19425. this._totalLightsCounter = new BABYLON.PerfCounter();
  19426. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19427. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19428. this._totalVertices = new BABYLON.PerfCounter();
  19429. this._activeIndices = new BABYLON.PerfCounter();
  19430. this._activeParticles = new BABYLON.PerfCounter();
  19431. this._lastFrameDuration = new BABYLON.PerfCounter();
  19432. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19433. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19434. this._particlesDuration = new BABYLON.PerfCounter();
  19435. this._renderDuration = new BABYLON.PerfCounter();
  19436. this._spritesDuration = new BABYLON.PerfCounter();
  19437. this._activeBones = new BABYLON.PerfCounter();
  19438. this._animationTime = 0;
  19439. this.animationTimeScale = 1;
  19440. this._renderId = 0;
  19441. this._executeWhenReadyTimeoutId = -1;
  19442. this._intermediateRendering = false;
  19443. this._toBeDisposed = new BABYLON.SmartArray(256);
  19444. this._pendingData = []; //ANY
  19445. this._activeMeshes = new BABYLON.SmartArray(256);
  19446. this._processedMaterials = new BABYLON.SmartArray(256);
  19447. this._renderTargets = new BABYLON.SmartArray(256);
  19448. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19449. this._activeSkeletons = new BABYLON.SmartArray(32);
  19450. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19451. this._activeAnimatables = new Array();
  19452. this._transformMatrix = BABYLON.Matrix.Zero();
  19453. this._edgesRenderers = new BABYLON.SmartArray(16);
  19454. this._uniqueIdCounter = 0;
  19455. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19456. this._engine.scenes.push(this);
  19457. this._externalData = new BABYLON.StringDictionary();
  19458. this._uid = null;
  19459. this._renderingManager = new BABYLON.RenderingManager(this);
  19460. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19461. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19462. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19463. if (BABYLON.OutlineRenderer) {
  19464. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19465. }
  19466. this.attachControl();
  19467. if (BABYLON.SoundTrack) {
  19468. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19469. }
  19470. //simplification queue
  19471. if (BABYLON.SimplificationQueue) {
  19472. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19473. }
  19474. //collision coordinator initialization. For now legacy per default.
  19475. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19476. }
  19477. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19478. get: function () {
  19479. return Scene._FOGMODE_NONE;
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19485. get: function () {
  19486. return Scene._FOGMODE_EXP;
  19487. },
  19488. enumerable: true,
  19489. configurable: true
  19490. });
  19491. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19492. get: function () {
  19493. return Scene._FOGMODE_EXP2;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19499. get: function () {
  19500. return Scene._FOGMODE_LINEAR;
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. Object.defineProperty(Scene.prototype, "onDispose", {
  19506. set: function (callback) {
  19507. if (this._onDisposeObserver) {
  19508. this.onDisposeObservable.remove(this._onDisposeObserver);
  19509. }
  19510. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(Scene.prototype, "beforeRender", {
  19516. set: function (callback) {
  19517. if (this._onBeforeRenderObserver) {
  19518. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19519. }
  19520. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(Scene.prototype, "afterRender", {
  19526. set: function (callback) {
  19527. if (this._onAfterRenderObserver) {
  19528. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19529. }
  19530. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19536. set: function (callback) {
  19537. if (this._onBeforeCameraRenderObserver) {
  19538. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19539. }
  19540. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19541. },
  19542. enumerable: true,
  19543. configurable: true
  19544. });
  19545. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19546. set: function (callback) {
  19547. if (this._onAfterCameraRenderObserver) {
  19548. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19549. }
  19550. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19551. },
  19552. enumerable: true,
  19553. configurable: true
  19554. });
  19555. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19556. get: function () {
  19557. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19563. get: function () {
  19564. if (!this._defaultMaterial) {
  19565. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19566. }
  19567. return this._defaultMaterial;
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19573. get: function () {
  19574. return this._frustumPlanes;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Scene.prototype, "debugLayer", {
  19580. // Properties
  19581. get: function () {
  19582. if (!this._debugLayer) {
  19583. this._debugLayer = new BABYLON.DebugLayer(this);
  19584. }
  19585. return this._debugLayer;
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19591. get: function () {
  19592. return this._workerCollisions;
  19593. },
  19594. set: function (enabled) {
  19595. enabled = (enabled && !!Worker);
  19596. this._workerCollisions = enabled;
  19597. if (this.collisionCoordinator) {
  19598. this.collisionCoordinator.destroy();
  19599. }
  19600. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19601. this.collisionCoordinator.init(this);
  19602. },
  19603. enumerable: true,
  19604. configurable: true
  19605. });
  19606. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19607. get: function () {
  19608. return this._selectionOctree;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19614. /**
  19615. * The mesh that is currently under the pointer.
  19616. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19617. */
  19618. get: function () {
  19619. return this._pointerOverMesh;
  19620. },
  19621. enumerable: true,
  19622. configurable: true
  19623. });
  19624. Object.defineProperty(Scene.prototype, "pointerX", {
  19625. /**
  19626. * Current on-screen X position of the pointer
  19627. * @return {number} X position of the pointer
  19628. */
  19629. get: function () {
  19630. return this._pointerX;
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. Object.defineProperty(Scene.prototype, "pointerY", {
  19636. /**
  19637. * Current on-screen Y position of the pointer
  19638. * @return {number} Y position of the pointer
  19639. */
  19640. get: function () {
  19641. return this._pointerY;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Scene.prototype.getCachedMaterial = function () {
  19647. return this._cachedMaterial;
  19648. };
  19649. Scene.prototype.getBoundingBoxRenderer = function () {
  19650. return this._boundingBoxRenderer;
  19651. };
  19652. Scene.prototype.getOutlineRenderer = function () {
  19653. return this._outlineRenderer;
  19654. };
  19655. Scene.prototype.getEngine = function () {
  19656. return this._engine;
  19657. };
  19658. Scene.prototype.getTotalVertices = function () {
  19659. return this._totalVertices.current;
  19660. };
  19661. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19662. get: function () {
  19663. return this._totalVertices;
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Scene.prototype.getActiveIndices = function () {
  19669. return this._activeIndices.current;
  19670. };
  19671. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19672. get: function () {
  19673. return this._activeIndices;
  19674. },
  19675. enumerable: true,
  19676. configurable: true
  19677. });
  19678. Scene.prototype.getActiveParticles = function () {
  19679. return this._activeParticles.current;
  19680. };
  19681. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19682. get: function () {
  19683. return this._activeParticles;
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Scene.prototype.getActiveBones = function () {
  19689. return this._activeBones.current;
  19690. };
  19691. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19692. get: function () {
  19693. return this._activeBones;
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. // Stats
  19699. Scene.prototype.getLastFrameDuration = function () {
  19700. return this._lastFrameDuration.current;
  19701. };
  19702. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19703. get: function () {
  19704. return this._lastFrameDuration;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19710. return this._evaluateActiveMeshesDuration.current;
  19711. };
  19712. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19713. get: function () {
  19714. return this._evaluateActiveMeshesDuration;
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Scene.prototype.getActiveMeshes = function () {
  19720. return this._activeMeshes;
  19721. };
  19722. Scene.prototype.getRenderTargetsDuration = function () {
  19723. return this._renderTargetsDuration.current;
  19724. };
  19725. Scene.prototype.getRenderDuration = function () {
  19726. return this._renderDuration.current;
  19727. };
  19728. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19729. get: function () {
  19730. return this._renderDuration;
  19731. },
  19732. enumerable: true,
  19733. configurable: true
  19734. });
  19735. Scene.prototype.getParticlesDuration = function () {
  19736. return this._particlesDuration.current;
  19737. };
  19738. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19739. get: function () {
  19740. return this._particlesDuration;
  19741. },
  19742. enumerable: true,
  19743. configurable: true
  19744. });
  19745. Scene.prototype.getSpritesDuration = function () {
  19746. return this._spritesDuration.current;
  19747. };
  19748. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19749. get: function () {
  19750. return this._spritesDuration;
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Scene.prototype.getAnimationRatio = function () {
  19756. return this._animationRatio;
  19757. };
  19758. Scene.prototype.getRenderId = function () {
  19759. return this._renderId;
  19760. };
  19761. Scene.prototype.incrementRenderId = function () {
  19762. this._renderId++;
  19763. };
  19764. Scene.prototype._updatePointerPosition = function (evt) {
  19765. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19766. this._pointerX = evt.clientX - canvasRect.left;
  19767. this._pointerY = evt.clientY - canvasRect.top;
  19768. this._unTranslatedPointerX = this._pointerX;
  19769. this._unTranslatedPointerY = this._pointerY;
  19770. if (this.cameraToUseForPointers) {
  19771. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  19772. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  19773. }
  19774. };
  19775. // Pointers handling
  19776. /**
  19777. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19778. * @param attachUp defines if you want to attach events to pointerup
  19779. * @param attachDown defines if you want to attach events to pointerdown
  19780. * @param attachMove defines if you want to attach events to pointermove
  19781. */
  19782. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19783. var _this = this;
  19784. if (attachUp === void 0) { attachUp = true; }
  19785. if (attachDown === void 0) { attachDown = true; }
  19786. if (attachMove === void 0) { attachMove = true; }
  19787. var spritePredicate = function (sprite) {
  19788. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19789. };
  19790. this._onPointerMove = function (evt) {
  19791. _this._updatePointerPosition(evt);
  19792. // PreObservable support
  19793. if (_this.onPrePointerObservable.hasObservers()) {
  19794. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19795. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19796. _this.onPrePointerObservable.notifyObservers(pi, type);
  19797. if (pi.skipOnPointerObservable) {
  19798. return;
  19799. }
  19800. }
  19801. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19802. return;
  19803. }
  19804. var canvas = _this._engine.getRenderingCanvas();
  19805. if (!_this.pointerMovePredicate) {
  19806. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19807. }
  19808. // Meshes
  19809. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19810. if (pickResult.hit && pickResult.pickedMesh) {
  19811. _this.setPointerOverSprite(null);
  19812. _this.setPointerOverMesh(pickResult.pickedMesh);
  19813. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19814. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  19815. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  19816. }
  19817. else {
  19818. canvas.style.cursor = _this.hoverCursor;
  19819. }
  19820. }
  19821. else {
  19822. canvas.style.cursor = "";
  19823. }
  19824. }
  19825. else {
  19826. _this.setPointerOverMesh(null);
  19827. // Sprites
  19828. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19829. if (pickResult.hit && pickResult.pickedSprite) {
  19830. _this.setPointerOverSprite(pickResult.pickedSprite);
  19831. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  19832. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  19833. }
  19834. else {
  19835. canvas.style.cursor = _this.hoverCursor;
  19836. }
  19837. }
  19838. else {
  19839. _this.setPointerOverSprite(null);
  19840. // Restore pointer
  19841. canvas.style.cursor = "";
  19842. }
  19843. }
  19844. if (_this.onPointerMove) {
  19845. _this.onPointerMove(evt, pickResult);
  19846. }
  19847. if (_this.onPointerObservable.hasObservers()) {
  19848. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  19849. var pi = new PointerInfo(type, evt, pickResult);
  19850. _this.onPointerObservable.notifyObservers(pi, type);
  19851. }
  19852. };
  19853. this._onPointerDown = function (evt) {
  19854. _this._updatePointerPosition(evt);
  19855. // PreObservable support
  19856. if (_this.onPrePointerObservable.hasObservers()) {
  19857. var type = PointerEventTypes.POINTERDOWN;
  19858. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19859. _this.onPrePointerObservable.notifyObservers(pi, type);
  19860. if (pi.skipOnPointerObservable) {
  19861. return;
  19862. }
  19863. }
  19864. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19865. return;
  19866. }
  19867. _this._startingPointerPosition.x = _this._pointerX;
  19868. _this._startingPointerPosition.y = _this._pointerY;
  19869. _this._startingPointerTime = new Date().getTime();
  19870. if (!_this.pointerDownPredicate) {
  19871. _this.pointerDownPredicate = function (mesh) {
  19872. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19873. };
  19874. }
  19875. // Meshes
  19876. _this._pickedDownMesh = null;
  19877. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19878. if (pickResult.hit && pickResult.pickedMesh) {
  19879. _this._pickedDownMesh = pickResult.pickedMesh;
  19880. if (pickResult.pickedMesh.actionManager) {
  19881. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  19882. switch (evt.button) {
  19883. case 0:
  19884. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19885. break;
  19886. case 1:
  19887. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19888. break;
  19889. case 2:
  19890. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19891. break;
  19892. }
  19893. if (pickResult.pickedMesh.actionManager) {
  19894. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19895. }
  19896. }
  19897. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19898. var that = _this;
  19899. window.setTimeout(function () {
  19900. 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);
  19901. if (pickResult.hit && pickResult.pickedMesh) {
  19902. if (pickResult.pickedMesh.actionManager) {
  19903. 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)) {
  19904. that._startingPointerTime = 0;
  19905. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19906. }
  19907. }
  19908. }
  19909. }, BABYLON.ActionManager.LongPressDelay);
  19910. }
  19911. }
  19912. }
  19913. if (_this.onPointerDown) {
  19914. _this.onPointerDown(evt, pickResult);
  19915. }
  19916. if (_this.onPointerObservable.hasObservers()) {
  19917. var type = PointerEventTypes.POINTERDOWN;
  19918. var pi = new PointerInfo(type, evt, pickResult);
  19919. _this.onPointerObservable.notifyObservers(pi, type);
  19920. }
  19921. // Sprites
  19922. _this._pickedDownSprite = null;
  19923. if (_this.spriteManagers.length > 0) {
  19924. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  19925. if (pickResult.hit && pickResult.pickedSprite) {
  19926. if (pickResult.pickedSprite.actionManager) {
  19927. _this._pickedDownSprite = pickResult.pickedSprite;
  19928. switch (evt.button) {
  19929. case 0:
  19930. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19931. break;
  19932. case 1:
  19933. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19934. break;
  19935. case 2:
  19936. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19937. break;
  19938. }
  19939. if (pickResult.pickedSprite.actionManager) {
  19940. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19941. }
  19942. }
  19943. }
  19944. }
  19945. };
  19946. this._onPointerUp = function (evt) {
  19947. _this._updatePointerPosition(evt);
  19948. // PreObservable support
  19949. if (_this.onPrePointerObservable.hasObservers()) {
  19950. var type = PointerEventTypes.POINTERUP;
  19951. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19952. _this.onPrePointerObservable.notifyObservers(pi, type);
  19953. if (pi.skipOnPointerObservable) {
  19954. return;
  19955. }
  19956. }
  19957. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19958. return;
  19959. }
  19960. if (!_this.pointerUpPredicate) {
  19961. _this.pointerUpPredicate = function (mesh) {
  19962. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  19963. };
  19964. }
  19965. // Meshes
  19966. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  19967. if (pickResult.hit && pickResult.pickedMesh) {
  19968. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  19969. if (_this.onPointerPick) {
  19970. _this.onPointerPick(evt, pickResult);
  19971. }
  19972. if (_this.onPointerObservable.hasObservers()) {
  19973. var type = PointerEventTypes.POINTERPICK;
  19974. var pi = new PointerInfo(type, evt, pickResult);
  19975. _this.onPointerObservable.notifyObservers(pi, type);
  19976. }
  19977. }
  19978. if (pickResult.pickedMesh.actionManager) {
  19979. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19980. if (pickResult.pickedMesh.actionManager) {
  19981. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  19982. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19983. }
  19984. }
  19985. }
  19986. }
  19987. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  19988. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  19989. }
  19990. if (_this.onPointerUp) {
  19991. _this.onPointerUp(evt, pickResult);
  19992. }
  19993. if (_this.onPointerObservable.hasObservers()) {
  19994. var type = PointerEventTypes.POINTERUP;
  19995. var pi = new PointerInfo(type, evt, pickResult);
  19996. _this.onPointerObservable.notifyObservers(pi, type);
  19997. }
  19998. _this._startingPointerTime = 0;
  19999. // Sprites
  20000. if (_this.spriteManagers.length > 0) {
  20001. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20002. if (pickResult.hit && pickResult.pickedSprite) {
  20003. if (pickResult.pickedSprite.actionManager) {
  20004. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20005. if (pickResult.pickedSprite.actionManager) {
  20006. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  20007. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20008. }
  20009. }
  20010. }
  20011. }
  20012. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  20013. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20014. }
  20015. }
  20016. };
  20017. this._onKeyDown = function (evt) {
  20018. if (_this.actionManager) {
  20019. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20020. }
  20021. };
  20022. this._onKeyUp = function (evt) {
  20023. if (_this.actionManager) {
  20024. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20025. }
  20026. };
  20027. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20028. var canvas = this._engine.getRenderingCanvas();
  20029. if (attachMove) {
  20030. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20031. // Wheel
  20032. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20033. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20034. }
  20035. if (attachDown) {
  20036. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20037. }
  20038. if (attachUp) {
  20039. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20040. }
  20041. canvas.tabIndex = 1;
  20042. canvas.addEventListener("keydown", this._onKeyDown, false);
  20043. canvas.addEventListener("keyup", this._onKeyUp, false);
  20044. };
  20045. Scene.prototype.detachControl = function () {
  20046. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20047. var canvas = this._engine.getRenderingCanvas();
  20048. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20049. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20050. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20051. // Wheel
  20052. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20053. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20054. canvas.removeEventListener("keydown", this._onKeyDown);
  20055. canvas.removeEventListener("keyup", this._onKeyUp);
  20056. };
  20057. // Ready
  20058. Scene.prototype.isReady = function () {
  20059. if (this._pendingData.length > 0) {
  20060. return false;
  20061. }
  20062. var index;
  20063. for (index = 0; index < this._geometries.length; index++) {
  20064. var geometry = this._geometries[index];
  20065. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20066. return false;
  20067. }
  20068. }
  20069. for (index = 0; index < this.meshes.length; index++) {
  20070. var mesh = this.meshes[index];
  20071. if (!mesh.isReady()) {
  20072. return false;
  20073. }
  20074. var mat = mesh.material;
  20075. if (mat) {
  20076. if (!mat.isReady(mesh)) {
  20077. return false;
  20078. }
  20079. }
  20080. }
  20081. return true;
  20082. };
  20083. Scene.prototype.resetCachedMaterial = function () {
  20084. this._cachedMaterial = null;
  20085. };
  20086. Scene.prototype.registerBeforeRender = function (func) {
  20087. this.onBeforeRenderObservable.add(func);
  20088. };
  20089. Scene.prototype.unregisterBeforeRender = function (func) {
  20090. this.onBeforeRenderObservable.removeCallback(func);
  20091. };
  20092. Scene.prototype.registerAfterRender = function (func) {
  20093. this.onAfterRenderObservable.add(func);
  20094. };
  20095. Scene.prototype.unregisterAfterRender = function (func) {
  20096. this.onAfterRenderObservable.removeCallback(func);
  20097. };
  20098. Scene.prototype._addPendingData = function (data) {
  20099. this._pendingData.push(data);
  20100. };
  20101. Scene.prototype._removePendingData = function (data) {
  20102. var index = this._pendingData.indexOf(data);
  20103. if (index !== -1) {
  20104. this._pendingData.splice(index, 1);
  20105. }
  20106. };
  20107. Scene.prototype.getWaitingItemsCount = function () {
  20108. return this._pendingData.length;
  20109. };
  20110. /**
  20111. * Registers a function to be executed when the scene is ready.
  20112. * @param {Function} func - the function to be executed.
  20113. */
  20114. Scene.prototype.executeWhenReady = function (func) {
  20115. var _this = this;
  20116. this.onReadyObservable.add(func);
  20117. if (this._executeWhenReadyTimeoutId !== -1) {
  20118. return;
  20119. }
  20120. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20121. _this._checkIsReady();
  20122. }, 150);
  20123. };
  20124. Scene.prototype._checkIsReady = function () {
  20125. var _this = this;
  20126. if (this.isReady()) {
  20127. this.onReadyObservable.notifyObservers(this);
  20128. this.onReadyObservable.clear();
  20129. this._executeWhenReadyTimeoutId = -1;
  20130. return;
  20131. }
  20132. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20133. _this._checkIsReady();
  20134. }, 150);
  20135. };
  20136. // Animations
  20137. /**
  20138. * Will start the animation sequence of a given target
  20139. * @param target - the target
  20140. * @param {number} from - from which frame should animation start
  20141. * @param {number} to - till which frame should animation run.
  20142. * @param {boolean} [loop] - should the animation loop
  20143. * @param {number} [speedRatio] - the speed in which to run the animation
  20144. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20145. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20146. * @return {BABYLON.Animatable} the animatable object created for this animation
  20147. * @see BABYLON.Animatable
  20148. * @see http://doc.babylonjs.com/page.php?p=22081
  20149. */
  20150. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20151. if (speedRatio === void 0) { speedRatio = 1.0; }
  20152. this.stopAnimation(target);
  20153. if (!animatable) {
  20154. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20155. }
  20156. // Local animations
  20157. if (target.animations) {
  20158. animatable.appendAnimations(target, target.animations);
  20159. }
  20160. // Children animations
  20161. if (target.getAnimatables) {
  20162. var animatables = target.getAnimatables();
  20163. for (var index = 0; index < animatables.length; index++) {
  20164. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20165. }
  20166. }
  20167. animatable.reset();
  20168. return animatable;
  20169. };
  20170. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20171. if (speedRatio === undefined) {
  20172. speedRatio = 1.0;
  20173. }
  20174. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20175. return animatable;
  20176. };
  20177. Scene.prototype.getAnimatableByTarget = function (target) {
  20178. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20179. if (this._activeAnimatables[index].target === target) {
  20180. return this._activeAnimatables[index];
  20181. }
  20182. }
  20183. return null;
  20184. };
  20185. Object.defineProperty(Scene.prototype, "Animatables", {
  20186. get: function () {
  20187. return this._activeAnimatables;
  20188. },
  20189. enumerable: true,
  20190. configurable: true
  20191. });
  20192. /**
  20193. * Will stop the animation of the given target
  20194. * @param target - the target
  20195. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20196. * @see beginAnimation
  20197. */
  20198. Scene.prototype.stopAnimation = function (target, animationName) {
  20199. var animatable = this.getAnimatableByTarget(target);
  20200. if (animatable) {
  20201. animatable.stop(animationName);
  20202. }
  20203. };
  20204. Scene.prototype._animate = function () {
  20205. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20206. return;
  20207. }
  20208. // Getting time
  20209. var now = BABYLON.Tools.Now;
  20210. if (!this._animationTimeLast) {
  20211. if (this._pendingData.length > 0) {
  20212. return;
  20213. }
  20214. this._animationTimeLast = now;
  20215. }
  20216. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20217. this._animationTime += deltaTime;
  20218. this._animationTimeLast = now;
  20219. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20220. this._activeAnimatables[index]._animate(this._animationTime);
  20221. }
  20222. };
  20223. // Matrix
  20224. Scene.prototype.getViewMatrix = function () {
  20225. return this._viewMatrix;
  20226. };
  20227. Scene.prototype.getProjectionMatrix = function () {
  20228. return this._projectionMatrix;
  20229. };
  20230. Scene.prototype.getTransformMatrix = function () {
  20231. return this._transformMatrix;
  20232. };
  20233. Scene.prototype.setTransformMatrix = function (view, projection) {
  20234. this._viewMatrix = view;
  20235. this._projectionMatrix = projection;
  20236. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20237. // Update frustum
  20238. if (!this._frustumPlanes) {
  20239. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20240. }
  20241. else {
  20242. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20243. }
  20244. };
  20245. // Methods
  20246. Scene.prototype.addMesh = function (newMesh) {
  20247. newMesh.uniqueId = this._uniqueIdCounter++;
  20248. var position = this.meshes.push(newMesh);
  20249. //notify the collision coordinator
  20250. this.collisionCoordinator.onMeshAdded(newMesh);
  20251. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20252. };
  20253. Scene.prototype.removeMesh = function (toRemove) {
  20254. var index = this.meshes.indexOf(toRemove);
  20255. if (index !== -1) {
  20256. // Remove from the scene if mesh found
  20257. this.meshes.splice(index, 1);
  20258. }
  20259. //notify the collision coordinator
  20260. this.collisionCoordinator.onMeshRemoved(toRemove);
  20261. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20262. return index;
  20263. };
  20264. Scene.prototype.removeSkeleton = function (toRemove) {
  20265. var index = this.skeletons.indexOf(toRemove);
  20266. if (index !== -1) {
  20267. // Remove from the scene if mesh found
  20268. this.skeletons.splice(index, 1);
  20269. }
  20270. return index;
  20271. };
  20272. Scene.prototype.removeLight = function (toRemove) {
  20273. var index = this.lights.indexOf(toRemove);
  20274. if (index !== -1) {
  20275. // Remove from the scene if mesh found
  20276. this.lights.splice(index, 1);
  20277. }
  20278. this.onLightRemovedObservable.notifyObservers(toRemove);
  20279. return index;
  20280. };
  20281. Scene.prototype.removeCamera = function (toRemove) {
  20282. var index = this.cameras.indexOf(toRemove);
  20283. if (index !== -1) {
  20284. // Remove from the scene if mesh found
  20285. this.cameras.splice(index, 1);
  20286. }
  20287. // Remove from activeCameras
  20288. var index2 = this.activeCameras.indexOf(toRemove);
  20289. if (index2 !== -1) {
  20290. // Remove from the scene if mesh found
  20291. this.activeCameras.splice(index2, 1);
  20292. }
  20293. // Reset the activeCamera
  20294. if (this.activeCamera === toRemove) {
  20295. if (this.cameras.length > 0) {
  20296. this.activeCamera = this.cameras[0];
  20297. }
  20298. else {
  20299. this.activeCamera = null;
  20300. }
  20301. }
  20302. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20303. return index;
  20304. };
  20305. Scene.prototype.addLight = function (newLight) {
  20306. newLight.uniqueId = this._uniqueIdCounter++;
  20307. var position = this.lights.push(newLight);
  20308. this.onNewLightAddedObservable.notifyObservers(newLight);
  20309. };
  20310. Scene.prototype.addCamera = function (newCamera) {
  20311. newCamera.uniqueId = this._uniqueIdCounter++;
  20312. var position = this.cameras.push(newCamera);
  20313. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20314. };
  20315. /**
  20316. * Switch active camera
  20317. * @param {Camera} newCamera - new active camera
  20318. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20319. */
  20320. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20321. if (attachControl === void 0) { attachControl = true; }
  20322. var canvas = this._engine.getRenderingCanvas();
  20323. this.activeCamera.detachControl(canvas);
  20324. this.activeCamera = newCamera;
  20325. if (attachControl) {
  20326. newCamera.attachControl(canvas);
  20327. }
  20328. };
  20329. /**
  20330. * sets the active camera of the scene using its ID
  20331. * @param {string} id - the camera's ID
  20332. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20333. * @see activeCamera
  20334. */
  20335. Scene.prototype.setActiveCameraByID = function (id) {
  20336. var camera = this.getCameraByID(id);
  20337. if (camera) {
  20338. this.activeCamera = camera;
  20339. return camera;
  20340. }
  20341. return null;
  20342. };
  20343. /**
  20344. * sets the active camera of the scene using its name
  20345. * @param {string} name - the camera's name
  20346. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20347. * @see activeCamera
  20348. */
  20349. Scene.prototype.setActiveCameraByName = function (name) {
  20350. var camera = this.getCameraByName(name);
  20351. if (camera) {
  20352. this.activeCamera = camera;
  20353. return camera;
  20354. }
  20355. return null;
  20356. };
  20357. /**
  20358. * get a material using its id
  20359. * @param {string} the material's ID
  20360. * @return {BABYLON.Material|null} the material or null if none found.
  20361. */
  20362. Scene.prototype.getMaterialByID = function (id) {
  20363. for (var index = 0; index < this.materials.length; index++) {
  20364. if (this.materials[index].id === id) {
  20365. return this.materials[index];
  20366. }
  20367. }
  20368. return null;
  20369. };
  20370. /**
  20371. * get a material using its name
  20372. * @param {string} the material's name
  20373. * @return {BABYLON.Material|null} the material or null if none found.
  20374. */
  20375. Scene.prototype.getMaterialByName = function (name) {
  20376. for (var index = 0; index < this.materials.length; index++) {
  20377. if (this.materials[index].name === name) {
  20378. return this.materials[index];
  20379. }
  20380. }
  20381. return null;
  20382. };
  20383. Scene.prototype.getLensFlareSystemByName = function (name) {
  20384. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20385. if (this.lensFlareSystems[index].name === name) {
  20386. return this.lensFlareSystems[index];
  20387. }
  20388. }
  20389. return null;
  20390. };
  20391. Scene.prototype.getLensFlareSystemByID = function (id) {
  20392. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20393. if (this.lensFlareSystems[index].id === id) {
  20394. return this.lensFlareSystems[index];
  20395. }
  20396. }
  20397. return null;
  20398. };
  20399. Scene.prototype.getCameraByID = function (id) {
  20400. for (var index = 0; index < this.cameras.length; index++) {
  20401. if (this.cameras[index].id === id) {
  20402. return this.cameras[index];
  20403. }
  20404. }
  20405. return null;
  20406. };
  20407. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20408. for (var index = 0; index < this.cameras.length; index++) {
  20409. if (this.cameras[index].uniqueId === uniqueId) {
  20410. return this.cameras[index];
  20411. }
  20412. }
  20413. return null;
  20414. };
  20415. /**
  20416. * get a camera using its name
  20417. * @param {string} the camera's name
  20418. * @return {BABYLON.Camera|null} the camera or null if none found.
  20419. */
  20420. Scene.prototype.getCameraByName = function (name) {
  20421. for (var index = 0; index < this.cameras.length; index++) {
  20422. if (this.cameras[index].name === name) {
  20423. return this.cameras[index];
  20424. }
  20425. }
  20426. return null;
  20427. };
  20428. /**
  20429. * get a bone using its id
  20430. * @param {string} the bone's id
  20431. * @return {BABYLON.Bone|null} the bone or null if not found
  20432. */
  20433. Scene.prototype.getBoneByID = function (id) {
  20434. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20435. var skeleton = this.skeletons[skeletonIndex];
  20436. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20437. if (skeleton.bones[boneIndex].id === id) {
  20438. return skeleton.bones[boneIndex];
  20439. }
  20440. }
  20441. }
  20442. return null;
  20443. };
  20444. /**
  20445. * get a bone using its id
  20446. * @param {string} the bone's name
  20447. * @return {BABYLON.Bone|null} the bone or null if not found
  20448. */
  20449. Scene.prototype.getBoneByName = function (name) {
  20450. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20451. var skeleton = this.skeletons[skeletonIndex];
  20452. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20453. if (skeleton.bones[boneIndex].name === name) {
  20454. return skeleton.bones[boneIndex];
  20455. }
  20456. }
  20457. }
  20458. return null;
  20459. };
  20460. /**
  20461. * get a light node using its name
  20462. * @param {string} the light's name
  20463. * @return {BABYLON.Light|null} the light or null if none found.
  20464. */
  20465. Scene.prototype.getLightByName = function (name) {
  20466. for (var index = 0; index < this.lights.length; index++) {
  20467. if (this.lights[index].name === name) {
  20468. return this.lights[index];
  20469. }
  20470. }
  20471. return null;
  20472. };
  20473. /**
  20474. * get a light node using its ID
  20475. * @param {string} the light's id
  20476. * @return {BABYLON.Light|null} the light or null if none found.
  20477. */
  20478. Scene.prototype.getLightByID = function (id) {
  20479. for (var index = 0; index < this.lights.length; index++) {
  20480. if (this.lights[index].id === id) {
  20481. return this.lights[index];
  20482. }
  20483. }
  20484. return null;
  20485. };
  20486. /**
  20487. * get a light node using its scene-generated unique ID
  20488. * @param {number} the light's unique id
  20489. * @return {BABYLON.Light|null} the light or null if none found.
  20490. */
  20491. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20492. for (var index = 0; index < this.lights.length; index++) {
  20493. if (this.lights[index].uniqueId === uniqueId) {
  20494. return this.lights[index];
  20495. }
  20496. }
  20497. return null;
  20498. };
  20499. /**
  20500. * get a particle system by id
  20501. * @param id {number} the particle system id
  20502. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20503. */
  20504. Scene.prototype.getParticleSystemByID = function (id) {
  20505. for (var index = 0; index < this.particleSystems.length; index++) {
  20506. if (this.particleSystems[index].id === id) {
  20507. return this.particleSystems[index];
  20508. }
  20509. }
  20510. return null;
  20511. };
  20512. /**
  20513. * get a geometry using its ID
  20514. * @param {string} the geometry's id
  20515. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20516. */
  20517. Scene.prototype.getGeometryByID = function (id) {
  20518. for (var index = 0; index < this._geometries.length; index++) {
  20519. if (this._geometries[index].id === id) {
  20520. return this._geometries[index];
  20521. }
  20522. }
  20523. return null;
  20524. };
  20525. /**
  20526. * add a new geometry to this scene.
  20527. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20528. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20529. * @return {boolean} was the geometry added or not
  20530. */
  20531. Scene.prototype.pushGeometry = function (geometry, force) {
  20532. if (!force && this.getGeometryByID(geometry.id)) {
  20533. return false;
  20534. }
  20535. this._geometries.push(geometry);
  20536. //notify the collision coordinator
  20537. this.collisionCoordinator.onGeometryAdded(geometry);
  20538. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20539. return true;
  20540. };
  20541. /**
  20542. * Removes an existing geometry
  20543. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20544. * @return {boolean} was the geometry removed or not
  20545. */
  20546. Scene.prototype.removeGeometry = function (geometry) {
  20547. var index = this._geometries.indexOf(geometry);
  20548. if (index > -1) {
  20549. this._geometries.splice(index, 1);
  20550. //notify the collision coordinator
  20551. this.collisionCoordinator.onGeometryDeleted(geometry);
  20552. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20553. return true;
  20554. }
  20555. return false;
  20556. };
  20557. Scene.prototype.getGeometries = function () {
  20558. return this._geometries;
  20559. };
  20560. /**
  20561. * Get the first added mesh found of a given ID
  20562. * @param {string} id - the id to search for
  20563. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20564. */
  20565. Scene.prototype.getMeshByID = function (id) {
  20566. for (var index = 0; index < this.meshes.length; index++) {
  20567. if (this.meshes[index].id === id) {
  20568. return this.meshes[index];
  20569. }
  20570. }
  20571. return null;
  20572. };
  20573. Scene.prototype.getMeshesByID = function (id) {
  20574. return this.meshes.filter(function (m) {
  20575. return m.id === id;
  20576. });
  20577. };
  20578. /**
  20579. * Get a mesh with its auto-generated unique id
  20580. * @param {number} uniqueId - the unique id to search for
  20581. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20582. */
  20583. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20584. for (var index = 0; index < this.meshes.length; index++) {
  20585. if (this.meshes[index].uniqueId === uniqueId) {
  20586. return this.meshes[index];
  20587. }
  20588. }
  20589. return null;
  20590. };
  20591. /**
  20592. * Get a the last added mesh found of a given ID
  20593. * @param {string} id - the id to search for
  20594. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20595. */
  20596. Scene.prototype.getLastMeshByID = function (id) {
  20597. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20598. if (this.meshes[index].id === id) {
  20599. return this.meshes[index];
  20600. }
  20601. }
  20602. return null;
  20603. };
  20604. /**
  20605. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20606. * @param {string} id - the id to search for
  20607. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20608. */
  20609. Scene.prototype.getLastEntryByID = function (id) {
  20610. var index;
  20611. for (index = this.meshes.length - 1; index >= 0; index--) {
  20612. if (this.meshes[index].id === id) {
  20613. return this.meshes[index];
  20614. }
  20615. }
  20616. for (index = this.cameras.length - 1; index >= 0; index--) {
  20617. if (this.cameras[index].id === id) {
  20618. return this.cameras[index];
  20619. }
  20620. }
  20621. for (index = this.lights.length - 1; index >= 0; index--) {
  20622. if (this.lights[index].id === id) {
  20623. return this.lights[index];
  20624. }
  20625. }
  20626. return null;
  20627. };
  20628. Scene.prototype.getNodeByID = function (id) {
  20629. var mesh = this.getMeshByID(id);
  20630. if (mesh) {
  20631. return mesh;
  20632. }
  20633. var light = this.getLightByID(id);
  20634. if (light) {
  20635. return light;
  20636. }
  20637. var camera = this.getCameraByID(id);
  20638. if (camera) {
  20639. return camera;
  20640. }
  20641. var bone = this.getBoneByID(id);
  20642. return bone;
  20643. };
  20644. Scene.prototype.getNodeByName = function (name) {
  20645. var mesh = this.getMeshByName(name);
  20646. if (mesh) {
  20647. return mesh;
  20648. }
  20649. var light = this.getLightByName(name);
  20650. if (light) {
  20651. return light;
  20652. }
  20653. var camera = this.getCameraByName(name);
  20654. if (camera) {
  20655. return camera;
  20656. }
  20657. var bone = this.getBoneByName(name);
  20658. return bone;
  20659. };
  20660. Scene.prototype.getMeshByName = function (name) {
  20661. for (var index = 0; index < this.meshes.length; index++) {
  20662. if (this.meshes[index].name === name) {
  20663. return this.meshes[index];
  20664. }
  20665. }
  20666. return null;
  20667. };
  20668. Scene.prototype.getSoundByName = function (name) {
  20669. var index;
  20670. if (BABYLON.AudioEngine) {
  20671. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20672. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20673. return this.mainSoundTrack.soundCollection[index];
  20674. }
  20675. }
  20676. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20677. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20678. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20679. return this.soundTracks[sdIndex].soundCollection[index];
  20680. }
  20681. }
  20682. }
  20683. }
  20684. return null;
  20685. };
  20686. Scene.prototype.getLastSkeletonByID = function (id) {
  20687. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20688. if (this.skeletons[index].id === id) {
  20689. return this.skeletons[index];
  20690. }
  20691. }
  20692. return null;
  20693. };
  20694. Scene.prototype.getSkeletonById = function (id) {
  20695. for (var index = 0; index < this.skeletons.length; index++) {
  20696. if (this.skeletons[index].id === id) {
  20697. return this.skeletons[index];
  20698. }
  20699. }
  20700. return null;
  20701. };
  20702. Scene.prototype.getSkeletonByName = function (name) {
  20703. for (var index = 0; index < this.skeletons.length; index++) {
  20704. if (this.skeletons[index].name === name) {
  20705. return this.skeletons[index];
  20706. }
  20707. }
  20708. return null;
  20709. };
  20710. Scene.prototype.isActiveMesh = function (mesh) {
  20711. return (this._activeMeshes.indexOf(mesh) !== -1);
  20712. };
  20713. /**
  20714. * Return a the first highlight layer of the scene with a given name.
  20715. * @param name The name of the highlight layer to look for.
  20716. * @return The highlight layer if found otherwise null.
  20717. */
  20718. Scene.prototype.getHighlightLayerByName = function (name) {
  20719. for (var index = 0; index < this.highlightLayers.length; index++) {
  20720. if (this.highlightLayers[index].name === name) {
  20721. return this.highlightLayers[index];
  20722. }
  20723. }
  20724. return null;
  20725. };
  20726. Object.defineProperty(Scene.prototype, "uid", {
  20727. /**
  20728. * Return a unique id as a string which can serve as an identifier for the scene
  20729. */
  20730. get: function () {
  20731. if (!this._uid) {
  20732. this._uid = BABYLON.Tools.RandomId();
  20733. }
  20734. return this._uid;
  20735. },
  20736. enumerable: true,
  20737. configurable: true
  20738. });
  20739. /**
  20740. * Add an externaly attached data from its key.
  20741. * This method call will fail and return false, if such key already exists.
  20742. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20743. * @param key the unique key that identifies the data
  20744. * @param data the data object to associate to the key for this Engine instance
  20745. * @return true if no such key were already present and the data was added successfully, false otherwise
  20746. */
  20747. Scene.prototype.addExternalData = function (key, data) {
  20748. return this._externalData.add(key, data);
  20749. };
  20750. /**
  20751. * Get an externaly attached data from its key
  20752. * @param key the unique key that identifies the data
  20753. * @return the associated data, if present (can be null), or undefined if not present
  20754. */
  20755. Scene.prototype.getExternalData = function (key) {
  20756. return this._externalData.get(key);
  20757. };
  20758. /**
  20759. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20760. * @param key the unique key that identifies the data
  20761. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20762. * @return the associated data, can be null if the factory returned null.
  20763. */
  20764. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20765. return this._externalData.getOrAddWithFactory(key, factory);
  20766. };
  20767. /**
  20768. * Remove an externaly attached data from the Engine instance
  20769. * @param key the unique key that identifies the data
  20770. * @return true if the data was successfully removed, false if it doesn't exist
  20771. */
  20772. Scene.prototype.removeExternalData = function (key) {
  20773. return this._externalData.remove(key);
  20774. };
  20775. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20776. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20777. var material = subMesh.getMaterial();
  20778. if (mesh.showSubMeshesBoundingBox) {
  20779. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  20780. }
  20781. if (material) {
  20782. // Render targets
  20783. if (material.getRenderTargetTextures) {
  20784. if (this._processedMaterials.indexOf(material) === -1) {
  20785. this._processedMaterials.push(material);
  20786. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20787. }
  20788. }
  20789. // Dispatch
  20790. this._activeIndices.addCount(subMesh.indexCount, false);
  20791. this._renderingManager.dispatch(subMesh);
  20792. }
  20793. }
  20794. };
  20795. Scene.prototype._isInIntermediateRendering = function () {
  20796. return this._intermediateRendering;
  20797. };
  20798. Scene.prototype._evaluateActiveMeshes = function () {
  20799. this.activeCamera._activeMeshes.reset();
  20800. this._activeMeshes.reset();
  20801. this._renderingManager.reset();
  20802. this._processedMaterials.reset();
  20803. this._activeParticleSystems.reset();
  20804. this._activeSkeletons.reset();
  20805. this._softwareSkinnedMeshes.reset();
  20806. this._boundingBoxRenderer.reset();
  20807. this._edgesRenderers.reset();
  20808. // Meshes
  20809. var meshes;
  20810. var len;
  20811. if (this._selectionOctree) {
  20812. var selection = this._selectionOctree.select(this._frustumPlanes);
  20813. meshes = selection.data;
  20814. len = selection.length;
  20815. }
  20816. else {
  20817. len = this.meshes.length;
  20818. meshes = this.meshes;
  20819. }
  20820. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20821. var mesh = meshes[meshIndex];
  20822. if (mesh.isBlocked) {
  20823. continue;
  20824. }
  20825. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20826. if (!mesh.isReady() || !mesh.isEnabled()) {
  20827. continue;
  20828. }
  20829. mesh.computeWorldMatrix();
  20830. // Intersections
  20831. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20832. this._meshesForIntersections.pushNoDuplicate(mesh);
  20833. }
  20834. // Switch to current LOD
  20835. var meshLOD = mesh.getLOD(this.activeCamera);
  20836. if (!meshLOD) {
  20837. continue;
  20838. }
  20839. mesh._preActivate();
  20840. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20841. this._activeMeshes.push(mesh);
  20842. this.activeCamera._activeMeshes.push(mesh);
  20843. mesh._activate(this._renderId);
  20844. this._activeMesh(mesh, meshLOD);
  20845. }
  20846. }
  20847. // Particle systems
  20848. this._particlesDuration.beginMonitoring();
  20849. var beforeParticlesDate = BABYLON.Tools.Now;
  20850. if (this.particlesEnabled) {
  20851. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  20852. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20853. var particleSystem = this.particleSystems[particleIndex];
  20854. if (!particleSystem.isStarted()) {
  20855. continue;
  20856. }
  20857. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  20858. this._activeParticleSystems.push(particleSystem);
  20859. particleSystem.animate();
  20860. this._renderingManager.dispatchParticles(particleSystem);
  20861. }
  20862. }
  20863. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  20864. }
  20865. this._particlesDuration.endMonitoring(false);
  20866. };
  20867. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20868. if (mesh.skeleton && this.skeletonsEnabled) {
  20869. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20870. mesh.skeleton.prepare();
  20871. }
  20872. if (!mesh.computeBonesUsingShaders) {
  20873. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20874. }
  20875. }
  20876. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20877. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  20878. }
  20879. if (sourceMesh._edgesRenderer) {
  20880. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  20881. }
  20882. if (mesh && mesh.subMeshes) {
  20883. // Submeshes Octrees
  20884. var len;
  20885. var subMeshes;
  20886. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20887. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20888. len = intersections.length;
  20889. subMeshes = intersections.data;
  20890. }
  20891. else {
  20892. subMeshes = mesh.subMeshes;
  20893. len = subMeshes.length;
  20894. }
  20895. for (var subIndex = 0; subIndex < len; subIndex++) {
  20896. var subMesh = subMeshes[subIndex];
  20897. this._evaluateSubMesh(subMesh, mesh);
  20898. }
  20899. }
  20900. };
  20901. Scene.prototype.updateTransformMatrix = function (force) {
  20902. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20903. };
  20904. Scene.prototype._renderForCamera = function (camera) {
  20905. var engine = this._engine;
  20906. var startTime = BABYLON.Tools.Now;
  20907. this.activeCamera = camera;
  20908. if (!this.activeCamera)
  20909. throw new Error("Active camera not set");
  20910. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20911. // Viewport
  20912. engine.setViewport(this.activeCamera.viewport);
  20913. // Camera
  20914. this.resetCachedMaterial();
  20915. this._renderId++;
  20916. this.updateTransformMatrix();
  20917. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20918. // Meshes
  20919. this._evaluateActiveMeshesDuration.beginMonitoring();
  20920. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  20921. this._evaluateActiveMeshes();
  20922. this._evaluateActiveMeshesDuration.endMonitoring(false);
  20923. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  20924. // Software skinning
  20925. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20926. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20927. mesh.applySkeleton(mesh.skeleton);
  20928. }
  20929. // Render targets
  20930. this._renderTargetsDuration.beginMonitoring();
  20931. var needsRestoreFrameBuffer = false;
  20932. var beforeRenderTargetDate = BABYLON.Tools.Now;
  20933. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20934. this._intermediateRendering = true;
  20935. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20936. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20937. var renderTarget = this._renderTargets.data[renderIndex];
  20938. if (renderTarget._shouldRender()) {
  20939. this._renderId++;
  20940. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20941. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20942. }
  20943. }
  20944. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20945. this._intermediateRendering = false;
  20946. this._renderId++;
  20947. needsRestoreFrameBuffer = true; // Restore back buffer
  20948. }
  20949. // Render HighlightLayer Texture
  20950. var stencilState = this._engine.getStencilBuffer();
  20951. var renderhighlights = false;
  20952. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20953. this._intermediateRendering = true;
  20954. for (var i = 0; i < this.highlightLayers.length; i++) {
  20955. var highlightLayer = this.highlightLayers[i];
  20956. if (highlightLayer.shouldRender() &&
  20957. (!highlightLayer.camera ||
  20958. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20959. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20960. renderhighlights = true;
  20961. var renderTarget = highlightLayer._mainTexture;
  20962. if (renderTarget._shouldRender()) {
  20963. this._renderId++;
  20964. renderTarget.render(false, false);
  20965. needsRestoreFrameBuffer = true;
  20966. }
  20967. }
  20968. }
  20969. this._intermediateRendering = false;
  20970. this._renderId++;
  20971. }
  20972. if (needsRestoreFrameBuffer) {
  20973. engine.restoreDefaultFramebuffer();
  20974. }
  20975. this._renderTargetsDuration.endMonitoring(false);
  20976. // Prepare Frame
  20977. this.postProcessManager._prepareFrame();
  20978. this._renderDuration.beginMonitoring();
  20979. // Backgrounds
  20980. var layerIndex;
  20981. var layer;
  20982. if (this.layers.length) {
  20983. engine.setDepthBuffer(false);
  20984. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20985. layer = this.layers[layerIndex];
  20986. if (layer.isBackground) {
  20987. layer.render();
  20988. }
  20989. }
  20990. engine.setDepthBuffer(true);
  20991. }
  20992. // Render
  20993. BABYLON.Tools.StartPerformanceCounter("Main render");
  20994. // Activate HighlightLayer stencil
  20995. if (renderhighlights) {
  20996. this._engine.setStencilBuffer(true);
  20997. }
  20998. this._renderingManager.render(null, null, true, true);
  20999. // Restore HighlightLayer stencil
  21000. if (renderhighlights) {
  21001. this._engine.setStencilBuffer(stencilState);
  21002. }
  21003. BABYLON.Tools.EndPerformanceCounter("Main render");
  21004. // Bounding boxes
  21005. this._boundingBoxRenderer.render();
  21006. // Edges
  21007. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21008. this._edgesRenderers.data[edgesRendererIndex].render();
  21009. }
  21010. // Lens flares
  21011. if (this.lensFlaresEnabled) {
  21012. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21013. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21014. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21015. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21016. lensFlareSystem.render();
  21017. }
  21018. }
  21019. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21020. }
  21021. // Foregrounds
  21022. if (this.layers.length) {
  21023. engine.setDepthBuffer(false);
  21024. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21025. layer = this.layers[layerIndex];
  21026. if (!layer.isBackground) {
  21027. layer.render();
  21028. }
  21029. }
  21030. engine.setDepthBuffer(true);
  21031. }
  21032. // Highlight Layer
  21033. if (renderhighlights) {
  21034. engine.setDepthBuffer(false);
  21035. for (var i = 0; i < this.highlightLayers.length; i++) {
  21036. if (this.highlightLayers[i].shouldRender()) {
  21037. this.highlightLayers[i].render();
  21038. }
  21039. }
  21040. engine.setDepthBuffer(true);
  21041. }
  21042. this._renderDuration.endMonitoring(false);
  21043. // Finalize frame
  21044. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21045. // Update camera
  21046. this.activeCamera._updateFromScene();
  21047. // Reset some special arrays
  21048. this._renderTargets.reset();
  21049. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21050. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21051. };
  21052. Scene.prototype._processSubCameras = function (camera) {
  21053. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21054. this._renderForCamera(camera);
  21055. return;
  21056. }
  21057. // rig cameras
  21058. for (var index = 0; index < camera._rigCameras.length; index++) {
  21059. this._renderForCamera(camera._rigCameras[index]);
  21060. }
  21061. this.activeCamera = camera;
  21062. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21063. // Update camera
  21064. this.activeCamera._updateFromScene();
  21065. };
  21066. Scene.prototype._checkIntersections = function () {
  21067. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21068. var sourceMesh = this._meshesForIntersections.data[index];
  21069. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21070. var action = sourceMesh.actionManager.actions[actionIndex];
  21071. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21072. var parameters = action.getTriggerParameter();
  21073. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21074. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21075. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21076. if (areIntersecting && currentIntersectionInProgress === -1) {
  21077. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21078. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21079. sourceMesh._intersectionsInProgress.push(otherMesh);
  21080. }
  21081. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21082. sourceMesh._intersectionsInProgress.push(otherMesh);
  21083. }
  21084. }
  21085. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21086. //They intersected, and now they don't.
  21087. //is this trigger an exit trigger? execute an event.
  21088. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21089. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21090. }
  21091. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21092. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21093. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21094. }
  21095. }
  21096. }
  21097. }
  21098. }
  21099. };
  21100. Scene.prototype.render = function () {
  21101. this._lastFrameDuration.beginMonitoring();
  21102. this._particlesDuration.fetchNewFrame();
  21103. this._spritesDuration.fetchNewFrame();
  21104. this._activeParticles.fetchNewFrame();
  21105. this._renderDuration.fetchNewFrame();
  21106. this._renderTargetsDuration.fetchNewFrame();
  21107. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21108. this._totalVertices.fetchNewFrame();
  21109. this._activeIndices.fetchNewFrame();
  21110. this._activeBones.fetchNewFrame();
  21111. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21112. this._meshesForIntersections.reset();
  21113. this.resetCachedMaterial();
  21114. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21115. // Actions
  21116. if (this.actionManager) {
  21117. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21118. }
  21119. //Simplification Queue
  21120. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21121. this.simplificationQueue.executeNext();
  21122. }
  21123. // Animations
  21124. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21125. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21126. this._animate();
  21127. // Physics
  21128. if (this._physicsEngine) {
  21129. BABYLON.Tools.StartPerformanceCounter("Physics");
  21130. this._physicsEngine._step(deltaTime / 1000.0);
  21131. BABYLON.Tools.EndPerformanceCounter("Physics");
  21132. }
  21133. // Before render
  21134. this.onBeforeRenderObservable.notifyObservers(this);
  21135. // Customs render targets
  21136. this._renderTargetsDuration.beginMonitoring();
  21137. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21138. var engine = this.getEngine();
  21139. var currentActiveCamera = this.activeCamera;
  21140. if (this.renderTargetsEnabled) {
  21141. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21142. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21143. var renderTarget = this.customRenderTargets[customIndex];
  21144. if (renderTarget._shouldRender()) {
  21145. this._renderId++;
  21146. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21147. if (!this.activeCamera)
  21148. throw new Error("Active camera not set");
  21149. // Viewport
  21150. engine.setViewport(this.activeCamera.viewport);
  21151. // Camera
  21152. this.updateTransformMatrix();
  21153. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21154. }
  21155. }
  21156. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21157. this._renderId++;
  21158. }
  21159. if (this.customRenderTargets.length > 0) {
  21160. engine.restoreDefaultFramebuffer();
  21161. }
  21162. this._renderTargetsDuration.endMonitoring();
  21163. this.activeCamera = currentActiveCamera;
  21164. // Procedural textures
  21165. if (this.proceduralTexturesEnabled) {
  21166. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21167. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21168. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21169. if (proceduralTexture._shouldRender()) {
  21170. proceduralTexture.render();
  21171. }
  21172. }
  21173. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21174. }
  21175. // Clear
  21176. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21177. // Shadows
  21178. if (this.shadowsEnabled) {
  21179. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21180. var light = this.lights[lightIndex];
  21181. var shadowGenerator = light.getShadowGenerator();
  21182. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21183. this._renderTargets.push(shadowGenerator.getShadowMap());
  21184. }
  21185. }
  21186. }
  21187. // Depth renderer
  21188. if (this._depthRenderer) {
  21189. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21190. }
  21191. // RenderPipeline
  21192. this.postProcessRenderPipelineManager.update();
  21193. // Multi-cameras?
  21194. if (this.activeCameras.length > 0) {
  21195. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21196. if (cameraIndex > 0) {
  21197. this._engine.clear(null, false, true, true);
  21198. }
  21199. this._processSubCameras(this.activeCameras[cameraIndex]);
  21200. }
  21201. }
  21202. else {
  21203. if (!this.activeCamera) {
  21204. throw new Error("No camera defined");
  21205. }
  21206. this._processSubCameras(this.activeCamera);
  21207. }
  21208. // Intersection checks
  21209. this._checkIntersections();
  21210. // Update the audio listener attached to the camera
  21211. if (BABYLON.AudioEngine) {
  21212. this._updateAudioParameters();
  21213. }
  21214. // After render
  21215. if (this.afterRender) {
  21216. this.afterRender();
  21217. }
  21218. this.onAfterRenderObservable.notifyObservers(this);
  21219. // Cleaning
  21220. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21221. this._toBeDisposed.data[index].dispose();
  21222. this._toBeDisposed[index] = null;
  21223. }
  21224. this._toBeDisposed.reset();
  21225. if (this.dumpNextRenderTargets) {
  21226. this.dumpNextRenderTargets = false;
  21227. }
  21228. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21229. this._lastFrameDuration.endMonitoring();
  21230. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21231. this._totalLightsCounter.addCount(this.lights.length, true);
  21232. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21233. this._totalTexturesCounter.addCount(this.textures.length, true);
  21234. this._activeBones.addCount(0, true);
  21235. this._activeIndices.addCount(0, true);
  21236. this._activeParticles.addCount(0, true);
  21237. };
  21238. Scene.prototype._updateAudioParameters = function () {
  21239. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21240. return;
  21241. }
  21242. var listeningCamera;
  21243. var audioEngine = BABYLON.Engine.audioEngine;
  21244. if (this.activeCameras.length > 0) {
  21245. listeningCamera = this.activeCameras[0];
  21246. }
  21247. else {
  21248. listeningCamera = this.activeCamera;
  21249. }
  21250. if (listeningCamera && audioEngine.canUseWebAudio) {
  21251. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21252. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21253. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21254. cameraDirection.normalize();
  21255. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21256. var i;
  21257. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21258. var sound = this.mainSoundTrack.soundCollection[i];
  21259. if (sound.useCustomAttenuation) {
  21260. sound.updateDistanceFromListener();
  21261. }
  21262. }
  21263. for (i = 0; i < this.soundTracks.length; i++) {
  21264. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21265. sound = this.soundTracks[i].soundCollection[j];
  21266. if (sound.useCustomAttenuation) {
  21267. sound.updateDistanceFromListener();
  21268. }
  21269. }
  21270. }
  21271. }
  21272. };
  21273. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21274. // Audio
  21275. get: function () {
  21276. return this._audioEnabled;
  21277. },
  21278. set: function (value) {
  21279. this._audioEnabled = value;
  21280. if (BABYLON.AudioEngine) {
  21281. if (this._audioEnabled) {
  21282. this._enableAudio();
  21283. }
  21284. else {
  21285. this._disableAudio();
  21286. }
  21287. }
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Scene.prototype._disableAudio = function () {
  21293. var i;
  21294. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21295. this.mainSoundTrack.soundCollection[i].pause();
  21296. }
  21297. for (i = 0; i < this.soundTracks.length; i++) {
  21298. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21299. this.soundTracks[i].soundCollection[j].pause();
  21300. }
  21301. }
  21302. };
  21303. Scene.prototype._enableAudio = function () {
  21304. var i;
  21305. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21306. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21307. this.mainSoundTrack.soundCollection[i].play();
  21308. }
  21309. }
  21310. for (i = 0; i < this.soundTracks.length; i++) {
  21311. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21312. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21313. this.soundTracks[i].soundCollection[j].play();
  21314. }
  21315. }
  21316. }
  21317. };
  21318. Object.defineProperty(Scene.prototype, "headphone", {
  21319. get: function () {
  21320. return this._headphone;
  21321. },
  21322. set: function (value) {
  21323. this._headphone = value;
  21324. if (BABYLON.AudioEngine) {
  21325. if (this._headphone) {
  21326. this._switchAudioModeForHeadphones();
  21327. }
  21328. else {
  21329. this._switchAudioModeForNormalSpeakers();
  21330. }
  21331. }
  21332. },
  21333. enumerable: true,
  21334. configurable: true
  21335. });
  21336. Scene.prototype._switchAudioModeForHeadphones = function () {
  21337. this.mainSoundTrack.switchPanningModelToHRTF();
  21338. for (var i = 0; i < this.soundTracks.length; i++) {
  21339. this.soundTracks[i].switchPanningModelToHRTF();
  21340. }
  21341. };
  21342. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21343. this.mainSoundTrack.switchPanningModelToEqualPower();
  21344. for (var i = 0; i < this.soundTracks.length; i++) {
  21345. this.soundTracks[i].switchPanningModelToEqualPower();
  21346. }
  21347. };
  21348. Scene.prototype.enableDepthRenderer = function () {
  21349. if (this._depthRenderer) {
  21350. return this._depthRenderer;
  21351. }
  21352. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21353. return this._depthRenderer;
  21354. };
  21355. Scene.prototype.disableDepthRenderer = function () {
  21356. if (!this._depthRenderer) {
  21357. return;
  21358. }
  21359. this._depthRenderer.dispose();
  21360. this._depthRenderer = null;
  21361. };
  21362. Scene.prototype.freezeMaterials = function () {
  21363. for (var i = 0; i < this.materials.length; i++) {
  21364. this.materials[i].freeze();
  21365. }
  21366. };
  21367. Scene.prototype.unfreezeMaterials = function () {
  21368. for (var i = 0; i < this.materials.length; i++) {
  21369. this.materials[i].unfreeze();
  21370. }
  21371. };
  21372. Scene.prototype.dispose = function () {
  21373. this.beforeRender = null;
  21374. this.afterRender = null;
  21375. this.skeletons = [];
  21376. this._boundingBoxRenderer.dispose();
  21377. if (this._depthRenderer) {
  21378. this._depthRenderer.dispose();
  21379. }
  21380. // Debug layer
  21381. if (this._debugLayer) {
  21382. this._debugLayer.hide();
  21383. }
  21384. // Events
  21385. this.onDisposeObservable.notifyObservers(this);
  21386. this.onDisposeObservable.clear();
  21387. this.onBeforeRenderObservable.clear();
  21388. this.onAfterRenderObservable.clear();
  21389. this.detachControl();
  21390. // Release sounds & sounds tracks
  21391. if (BABYLON.AudioEngine) {
  21392. this.disposeSounds();
  21393. }
  21394. // Detach cameras
  21395. var canvas = this._engine.getRenderingCanvas();
  21396. var index;
  21397. for (index = 0; index < this.cameras.length; index++) {
  21398. this.cameras[index].detachControl(canvas);
  21399. }
  21400. // Release lights
  21401. while (this.lights.length) {
  21402. this.lights[0].dispose();
  21403. }
  21404. // Release meshes
  21405. while (this.meshes.length) {
  21406. this.meshes[0].dispose(true);
  21407. }
  21408. // Release cameras
  21409. while (this.cameras.length) {
  21410. this.cameras[0].dispose();
  21411. }
  21412. // Release materials
  21413. while (this.materials.length) {
  21414. this.materials[0].dispose();
  21415. }
  21416. // Release particles
  21417. while (this.particleSystems.length) {
  21418. this.particleSystems[0].dispose();
  21419. }
  21420. // Release sprites
  21421. while (this.spriteManagers.length) {
  21422. this.spriteManagers[0].dispose();
  21423. }
  21424. // Release layers
  21425. while (this.layers.length) {
  21426. this.layers[0].dispose();
  21427. }
  21428. while (this.highlightLayers.length) {
  21429. this.highlightLayers[0].dispose();
  21430. }
  21431. // Release textures
  21432. while (this.textures.length) {
  21433. this.textures[0].dispose();
  21434. }
  21435. // Post-processes
  21436. this.postProcessManager.dispose();
  21437. // Physics
  21438. if (this._physicsEngine) {
  21439. this.disablePhysicsEngine();
  21440. }
  21441. // Remove from engine
  21442. index = this._engine.scenes.indexOf(this);
  21443. if (index > -1) {
  21444. this._engine.scenes.splice(index, 1);
  21445. }
  21446. this._engine.wipeCaches();
  21447. };
  21448. // Release sounds & sounds tracks
  21449. Scene.prototype.disposeSounds = function () {
  21450. this.mainSoundTrack.dispose();
  21451. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21452. this.soundTracks[scIndex].dispose();
  21453. }
  21454. };
  21455. // Octrees
  21456. Scene.prototype.getWorldExtends = function () {
  21457. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21458. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21459. for (var index = 0; index < this.meshes.length; index++) {
  21460. var mesh = this.meshes[index];
  21461. mesh.computeWorldMatrix(true);
  21462. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21463. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21464. BABYLON.Tools.CheckExtends(minBox, min, max);
  21465. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21466. }
  21467. return {
  21468. min: min,
  21469. max: max
  21470. };
  21471. };
  21472. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21473. if (maxCapacity === void 0) { maxCapacity = 64; }
  21474. if (maxDepth === void 0) { maxDepth = 2; }
  21475. if (!this._selectionOctree) {
  21476. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21477. }
  21478. var worldExtends = this.getWorldExtends();
  21479. // Update octree
  21480. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21481. return this._selectionOctree;
  21482. };
  21483. // Picking
  21484. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21485. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21486. var engine = this._engine;
  21487. if (!camera) {
  21488. if (!this.activeCamera)
  21489. throw new Error("Active camera not set");
  21490. camera = this.activeCamera;
  21491. }
  21492. var cameraViewport = camera.viewport;
  21493. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21494. // Moving coordinates to local viewport world
  21495. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21496. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21497. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21498. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21499. };
  21500. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21501. var engine = this._engine;
  21502. if (!camera) {
  21503. if (!this.activeCamera)
  21504. throw new Error("Active camera not set");
  21505. camera = this.activeCamera;
  21506. }
  21507. var cameraViewport = camera.viewport;
  21508. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21509. var identity = BABYLON.Matrix.Identity();
  21510. // Moving coordinates to local viewport world
  21511. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21512. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21513. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21514. };
  21515. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21516. var pickingInfo = null;
  21517. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21518. var mesh = this.meshes[meshIndex];
  21519. if (predicate) {
  21520. if (!predicate(mesh)) {
  21521. continue;
  21522. }
  21523. }
  21524. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21525. continue;
  21526. }
  21527. var world = mesh.getWorldMatrix();
  21528. var ray = rayFunction(world);
  21529. var result = mesh.intersects(ray, fastCheck);
  21530. if (!result || !result.hit)
  21531. continue;
  21532. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21533. continue;
  21534. pickingInfo = result;
  21535. if (fastCheck) {
  21536. break;
  21537. }
  21538. }
  21539. return pickingInfo || new BABYLON.PickingInfo();
  21540. };
  21541. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21542. var pickingInfos = new Array();
  21543. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21544. var mesh = this.meshes[meshIndex];
  21545. if (predicate) {
  21546. if (!predicate(mesh)) {
  21547. continue;
  21548. }
  21549. }
  21550. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21551. continue;
  21552. }
  21553. var world = mesh.getWorldMatrix();
  21554. var ray = rayFunction(world);
  21555. var result = mesh.intersects(ray, false);
  21556. if (!result || !result.hit)
  21557. continue;
  21558. pickingInfos.push(result);
  21559. }
  21560. return pickingInfos;
  21561. };
  21562. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21563. var pickingInfo = null;
  21564. camera = camera || this.activeCamera;
  21565. if (this.spriteManagers.length > 0) {
  21566. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21567. var spriteManager = this.spriteManagers[spriteIndex];
  21568. if (!spriteManager.isPickable) {
  21569. continue;
  21570. }
  21571. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21572. if (!result || !result.hit)
  21573. continue;
  21574. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21575. continue;
  21576. pickingInfo = result;
  21577. if (fastCheck) {
  21578. break;
  21579. }
  21580. }
  21581. }
  21582. return pickingInfo || new BABYLON.PickingInfo();
  21583. };
  21584. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21585. /// <param name="x">X position on screen</param>
  21586. /// <param name="y">Y position on screen</param>
  21587. /// <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>
  21588. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21589. /// <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>
  21590. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21591. var _this = this;
  21592. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  21593. };
  21594. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21595. /// <param name="x">X position on screen</param>
  21596. /// <param name="y">Y position on screen</param>
  21597. /// <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>
  21598. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  21599. /// <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>
  21600. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21601. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  21602. };
  21603. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21604. var _this = this;
  21605. return this._internalPick(function (world) {
  21606. if (!_this._pickWithRayInverseMatrix) {
  21607. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21608. }
  21609. world.invertToRef(_this._pickWithRayInverseMatrix);
  21610. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21611. }, predicate, fastCheck);
  21612. };
  21613. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21614. /// <param name="x">X position on screen</param>
  21615. /// <param name="y">Y position on screen</param>
  21616. /// <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>
  21617. /// <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>
  21618. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21619. var _this = this;
  21620. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  21621. };
  21622. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  21623. /// <param name="ray">Ray to use</param>
  21624. /// <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>
  21625. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21626. var _this = this;
  21627. return this._internalMultiPick(function (world) {
  21628. if (!_this._pickWithRayInverseMatrix) {
  21629. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21630. }
  21631. world.invertToRef(_this._pickWithRayInverseMatrix);
  21632. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  21633. }, predicate);
  21634. };
  21635. Scene.prototype.setPointerOverMesh = function (mesh) {
  21636. if (this._pointerOverMesh === mesh) {
  21637. return;
  21638. }
  21639. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21640. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21641. }
  21642. this._pointerOverMesh = mesh;
  21643. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21644. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21645. }
  21646. };
  21647. Scene.prototype.getPointerOverMesh = function () {
  21648. return this._pointerOverMesh;
  21649. };
  21650. Scene.prototype.setPointerOverSprite = function (sprite) {
  21651. if (this._pointerOverSprite === sprite) {
  21652. return;
  21653. }
  21654. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21655. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21656. }
  21657. this._pointerOverSprite = sprite;
  21658. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21659. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21660. }
  21661. };
  21662. Scene.prototype.getPointerOverSprite = function () {
  21663. return this._pointerOverSprite;
  21664. };
  21665. // Physics
  21666. Scene.prototype.getPhysicsEngine = function () {
  21667. return this._physicsEngine;
  21668. };
  21669. /**
  21670. * Enables physics to the current scene
  21671. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21672. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21673. * @return {boolean} was the physics engine initialized
  21674. */
  21675. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21676. if (this._physicsEngine) {
  21677. return true;
  21678. }
  21679. try {
  21680. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21681. return true;
  21682. }
  21683. catch (e) {
  21684. BABYLON.Tools.Error(e.message);
  21685. return false;
  21686. }
  21687. };
  21688. Scene.prototype.disablePhysicsEngine = function () {
  21689. if (!this._physicsEngine) {
  21690. return;
  21691. }
  21692. this._physicsEngine.dispose();
  21693. this._physicsEngine = undefined;
  21694. };
  21695. Scene.prototype.isPhysicsEnabled = function () {
  21696. return this._physicsEngine !== undefined;
  21697. };
  21698. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21699. var mesh = compound.parts[0].mesh;
  21700. mesh.physicsImpostor.dispose();
  21701. mesh.physicsImpostor = null;
  21702. };
  21703. // Misc.
  21704. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  21705. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21706. // Light
  21707. if (this.lights.length === 0) {
  21708. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21709. }
  21710. // Camera
  21711. if (!this.activeCamera) {
  21712. // Compute position
  21713. var worldExtends = this.getWorldExtends();
  21714. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  21715. var camera;
  21716. if (createArcRotateCamera) {
  21717. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  21718. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  21719. camera.setTarget(worldCenter);
  21720. }
  21721. else {
  21722. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  21723. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  21724. camera.setTarget(worldCenter);
  21725. }
  21726. this.activeCamera = camera;
  21727. }
  21728. };
  21729. // Tags
  21730. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21731. if (tagsQuery === undefined) {
  21732. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21733. return list;
  21734. }
  21735. var listByTags = [];
  21736. forEach = forEach || (function (item) { return; });
  21737. for (var i in list) {
  21738. var item = list[i];
  21739. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21740. listByTags.push(item);
  21741. forEach(item);
  21742. }
  21743. }
  21744. return listByTags;
  21745. };
  21746. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21747. return this._getByTags(this.meshes, tagsQuery, forEach);
  21748. };
  21749. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21750. return this._getByTags(this.cameras, tagsQuery, forEach);
  21751. };
  21752. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21753. return this._getByTags(this.lights, tagsQuery, forEach);
  21754. };
  21755. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21756. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21757. };
  21758. /**
  21759. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21760. * This allowed control for front to back rendering or reversly depending of the special needs.
  21761. *
  21762. * @param renderingGroupId The rendering group id corresponding to its index
  21763. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21764. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21765. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21766. */
  21767. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21768. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21769. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21770. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21771. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21772. };
  21773. /**
  21774. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21775. *
  21776. * @param renderingGroupId The rendering group id corresponding to its index
  21777. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21778. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21779. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21780. */
  21781. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21782. if (depth === void 0) { depth = true; }
  21783. if (stencil === void 0) { stencil = true; }
  21784. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21785. };
  21786. return Scene;
  21787. }());
  21788. // Statics
  21789. Scene._FOGMODE_NONE = 0;
  21790. Scene._FOGMODE_EXP = 1;
  21791. Scene._FOGMODE_EXP2 = 2;
  21792. Scene._FOGMODE_LINEAR = 3;
  21793. Scene.MinDeltaTime = 1.0;
  21794. Scene.MaxDeltaTime = 1000.0;
  21795. BABYLON.Scene = Scene;
  21796. })(BABYLON || (BABYLON = {}));
  21797. //# sourceMappingURL=babylon.scene.js.map
  21798. var BABYLON;
  21799. (function (BABYLON) {
  21800. var Buffer = (function () {
  21801. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21802. if (engine instanceof BABYLON.Mesh) {
  21803. this._engine = engine.getScene().getEngine();
  21804. }
  21805. else {
  21806. this._engine = engine;
  21807. }
  21808. this._updatable = updatable;
  21809. this._data = data;
  21810. this._strideSize = stride;
  21811. if (!postponeInternalCreation) {
  21812. this.create();
  21813. }
  21814. this._instanced = instanced;
  21815. }
  21816. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21817. // a lot of these parameters are ignored as they are overriden by the buffer
  21818. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21819. };
  21820. // Properties
  21821. Buffer.prototype.isUpdatable = function () {
  21822. return this._updatable;
  21823. };
  21824. Buffer.prototype.getData = function () {
  21825. return this._data;
  21826. };
  21827. Buffer.prototype.getBuffer = function () {
  21828. return this._buffer;
  21829. };
  21830. Buffer.prototype.getStrideSize = function () {
  21831. return this._strideSize;
  21832. };
  21833. Buffer.prototype.getIsInstanced = function () {
  21834. return this._instanced;
  21835. };
  21836. // Methods
  21837. Buffer.prototype.create = function (data) {
  21838. if (!data && this._buffer) {
  21839. return; // nothing to do
  21840. }
  21841. data = data || this._data;
  21842. if (!this._buffer) {
  21843. if (this._updatable) {
  21844. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21845. this._data = data;
  21846. }
  21847. else {
  21848. this._buffer = this._engine.createVertexBuffer(data);
  21849. }
  21850. }
  21851. else if (this._updatable) {
  21852. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21853. this._data = data;
  21854. }
  21855. };
  21856. Buffer.prototype.update = function (data) {
  21857. this.create(data);
  21858. };
  21859. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21860. if (!this._buffer) {
  21861. return;
  21862. }
  21863. if (this._updatable) {
  21864. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21865. this._data = null;
  21866. }
  21867. };
  21868. Buffer.prototype.dispose = function () {
  21869. if (!this._buffer) {
  21870. return;
  21871. }
  21872. if (this._engine._releaseBuffer(this._buffer)) {
  21873. this._buffer = null;
  21874. }
  21875. };
  21876. return Buffer;
  21877. }());
  21878. BABYLON.Buffer = Buffer;
  21879. })(BABYLON || (BABYLON = {}));
  21880. //# sourceMappingURL=babylon.buffer.js.map
  21881. var BABYLON;
  21882. (function (BABYLON) {
  21883. var VertexBuffer = (function () {
  21884. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21885. if (!stride) {
  21886. // Deduce stride from kind
  21887. switch (kind) {
  21888. case VertexBuffer.PositionKind:
  21889. stride = 3;
  21890. break;
  21891. case VertexBuffer.NormalKind:
  21892. stride = 3;
  21893. break;
  21894. case VertexBuffer.UVKind:
  21895. case VertexBuffer.UV2Kind:
  21896. case VertexBuffer.UV3Kind:
  21897. case VertexBuffer.UV4Kind:
  21898. case VertexBuffer.UV5Kind:
  21899. case VertexBuffer.UV6Kind:
  21900. stride = 2;
  21901. break;
  21902. case VertexBuffer.ColorKind:
  21903. stride = 4;
  21904. break;
  21905. case VertexBuffer.MatricesIndicesKind:
  21906. case VertexBuffer.MatricesIndicesExtraKind:
  21907. stride = 4;
  21908. break;
  21909. case VertexBuffer.MatricesWeightsKind:
  21910. case VertexBuffer.MatricesWeightsExtraKind:
  21911. stride = 4;
  21912. break;
  21913. }
  21914. }
  21915. if (data instanceof BABYLON.Buffer) {
  21916. if (!stride) {
  21917. stride = data.getStrideSize();
  21918. }
  21919. this._buffer = data;
  21920. this._ownsBuffer = false;
  21921. }
  21922. else {
  21923. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21924. this._ownsBuffer = true;
  21925. }
  21926. this._stride = stride;
  21927. this._offset = offset ? offset : 0;
  21928. this._size = size ? size : stride;
  21929. this._kind = kind;
  21930. }
  21931. /**
  21932. * Returns the kind of the VertexBuffer (string).
  21933. */
  21934. VertexBuffer.prototype.getKind = function () {
  21935. return this._kind;
  21936. };
  21937. // Properties
  21938. /**
  21939. * Boolean : is the VertexBuffer updatable ?
  21940. */
  21941. VertexBuffer.prototype.isUpdatable = function () {
  21942. return this._buffer.isUpdatable();
  21943. };
  21944. /**
  21945. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21946. */
  21947. VertexBuffer.prototype.getData = function () {
  21948. return this._buffer.getData();
  21949. };
  21950. /**
  21951. * Returns the WebGLBuffer associated to the VertexBuffer.
  21952. */
  21953. VertexBuffer.prototype.getBuffer = function () {
  21954. return this._buffer.getBuffer();
  21955. };
  21956. /**
  21957. * Returns the stride of the VertexBuffer (integer).
  21958. */
  21959. VertexBuffer.prototype.getStrideSize = function () {
  21960. return this._stride;
  21961. };
  21962. /**
  21963. * Returns the offset (integer).
  21964. */
  21965. VertexBuffer.prototype.getOffset = function () {
  21966. return this._offset;
  21967. };
  21968. /**
  21969. * Returns the VertexBuffer total size (integer).
  21970. */
  21971. VertexBuffer.prototype.getSize = function () {
  21972. return this._size;
  21973. };
  21974. /**
  21975. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21976. */
  21977. VertexBuffer.prototype.getIsInstanced = function () {
  21978. return this._buffer.getIsInstanced();
  21979. };
  21980. // Methods
  21981. /**
  21982. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21983. * Returns the created WebGLBuffer.
  21984. */
  21985. VertexBuffer.prototype.create = function (data) {
  21986. return this._buffer.create(data);
  21987. };
  21988. /**
  21989. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21990. * Returns the updated WebGLBuffer.
  21991. */
  21992. VertexBuffer.prototype.update = function (data) {
  21993. return this._buffer.update(data);
  21994. };
  21995. /**
  21996. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21997. * Returns the directly updated WebGLBuffer.
  21998. */
  21999. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22000. return this._buffer.updateDirectly(data, offset);
  22001. };
  22002. /**
  22003. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22004. */
  22005. VertexBuffer.prototype.dispose = function () {
  22006. if (this._ownsBuffer) {
  22007. this._buffer.dispose();
  22008. }
  22009. };
  22010. Object.defineProperty(VertexBuffer, "PositionKind", {
  22011. get: function () {
  22012. return VertexBuffer._PositionKind;
  22013. },
  22014. enumerable: true,
  22015. configurable: true
  22016. });
  22017. Object.defineProperty(VertexBuffer, "NormalKind", {
  22018. get: function () {
  22019. return VertexBuffer._NormalKind;
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(VertexBuffer, "UVKind", {
  22025. get: function () {
  22026. return VertexBuffer._UVKind;
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22032. get: function () {
  22033. return VertexBuffer._UV2Kind;
  22034. },
  22035. enumerable: true,
  22036. configurable: true
  22037. });
  22038. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22039. get: function () {
  22040. return VertexBuffer._UV3Kind;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22046. get: function () {
  22047. return VertexBuffer._UV4Kind;
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22053. get: function () {
  22054. return VertexBuffer._UV5Kind;
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22060. get: function () {
  22061. return VertexBuffer._UV6Kind;
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(VertexBuffer, "ColorKind", {
  22067. get: function () {
  22068. return VertexBuffer._ColorKind;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22074. get: function () {
  22075. return VertexBuffer._MatricesIndicesKind;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22081. get: function () {
  22082. return VertexBuffer._MatricesWeightsKind;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22088. get: function () {
  22089. return VertexBuffer._MatricesIndicesExtraKind;
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22095. get: function () {
  22096. return VertexBuffer._MatricesWeightsExtraKind;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. return VertexBuffer;
  22102. }());
  22103. // Enums
  22104. VertexBuffer._PositionKind = "position";
  22105. VertexBuffer._NormalKind = "normal";
  22106. VertexBuffer._UVKind = "uv";
  22107. VertexBuffer._UV2Kind = "uv2";
  22108. VertexBuffer._UV3Kind = "uv3";
  22109. VertexBuffer._UV4Kind = "uv4";
  22110. VertexBuffer._UV5Kind = "uv5";
  22111. VertexBuffer._UV6Kind = "uv6";
  22112. VertexBuffer._ColorKind = "color";
  22113. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22114. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22115. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22116. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22117. BABYLON.VertexBuffer = VertexBuffer;
  22118. })(BABYLON || (BABYLON = {}));
  22119. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22120. var BABYLON;
  22121. (function (BABYLON) {
  22122. /**
  22123. * Creates an instance based on a source mesh.
  22124. */
  22125. var InstancedMesh = (function (_super) {
  22126. __extends(InstancedMesh, _super);
  22127. function InstancedMesh(name, source) {
  22128. var _this = _super.call(this, name, source.getScene()) || this;
  22129. source.instances.push(_this);
  22130. _this._sourceMesh = source;
  22131. _this.position.copyFrom(source.position);
  22132. _this.rotation.copyFrom(source.rotation);
  22133. _this.scaling.copyFrom(source.scaling);
  22134. if (source.rotationQuaternion) {
  22135. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22136. }
  22137. _this.infiniteDistance = source.infiniteDistance;
  22138. _this.setPivotMatrix(source.getPivotMatrix());
  22139. _this.refreshBoundingInfo();
  22140. _this._syncSubMeshes();
  22141. return _this;
  22142. }
  22143. /**
  22144. * Returns the string "InstancedMesh".
  22145. */
  22146. InstancedMesh.prototype.getClassName = function () {
  22147. return "InstancedMesh";
  22148. };
  22149. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22150. // Methods
  22151. get: function () {
  22152. return this._sourceMesh.receiveShadows;
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Object.defineProperty(InstancedMesh.prototype, "material", {
  22158. get: function () {
  22159. return this._sourceMesh.material;
  22160. },
  22161. enumerable: true,
  22162. configurable: true
  22163. });
  22164. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22165. get: function () {
  22166. return this._sourceMesh.visibility;
  22167. },
  22168. enumerable: true,
  22169. configurable: true
  22170. });
  22171. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22172. get: function () {
  22173. return this._sourceMesh.skeleton;
  22174. },
  22175. enumerable: true,
  22176. configurable: true
  22177. });
  22178. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22179. get: function () {
  22180. return this._sourceMesh.renderingGroupId;
  22181. },
  22182. enumerable: true,
  22183. configurable: true
  22184. });
  22185. /**
  22186. * Returns the total number of vertices (integer).
  22187. */
  22188. InstancedMesh.prototype.getTotalVertices = function () {
  22189. return this._sourceMesh.getTotalVertices();
  22190. };
  22191. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22192. get: function () {
  22193. return this._sourceMesh;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. /**
  22199. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22200. */
  22201. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22202. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22203. };
  22204. /**
  22205. * Boolean : True if the mesh owns the requested kind of data.
  22206. */
  22207. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22208. return this._sourceMesh.isVerticesDataPresent(kind);
  22209. };
  22210. /**
  22211. * Returns an array of indices (IndicesArray).
  22212. */
  22213. InstancedMesh.prototype.getIndices = function () {
  22214. return this._sourceMesh.getIndices();
  22215. };
  22216. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22217. get: function () {
  22218. return this._sourceMesh._positions;
  22219. },
  22220. enumerable: true,
  22221. configurable: true
  22222. });
  22223. /**
  22224. * Sets a new updated BoundingInfo to the mesh.
  22225. * Returns the mesh.
  22226. */
  22227. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22228. var meshBB = this._sourceMesh.getBoundingInfo();
  22229. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22230. this._updateBoundingInfo();
  22231. return this;
  22232. };
  22233. InstancedMesh.prototype._preActivate = function () {
  22234. if (this._currentLOD) {
  22235. this._currentLOD._preActivate();
  22236. }
  22237. return this;
  22238. };
  22239. InstancedMesh.prototype._activate = function (renderId) {
  22240. if (this._currentLOD) {
  22241. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22242. }
  22243. return this;
  22244. };
  22245. /**
  22246. * Returns the current associated LOD AbstractMesh.
  22247. */
  22248. InstancedMesh.prototype.getLOD = function (camera) {
  22249. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22250. if (this._currentLOD === this.sourceMesh) {
  22251. return this;
  22252. }
  22253. return this._currentLOD;
  22254. };
  22255. InstancedMesh.prototype._syncSubMeshes = function () {
  22256. this.releaseSubMeshes();
  22257. if (this._sourceMesh.subMeshes) {
  22258. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22259. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22260. }
  22261. }
  22262. return this;
  22263. };
  22264. InstancedMesh.prototype._generatePointsArray = function () {
  22265. return this._sourceMesh._generatePointsArray();
  22266. };
  22267. /**
  22268. * Creates a new InstancedMesh from the current mesh.
  22269. * - name (string) : the cloned mesh name
  22270. * - newParent (optional Node) : the optional Node to parent the clone to.
  22271. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22272. *
  22273. * Returns the clone.
  22274. */
  22275. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22276. var result = this._sourceMesh.createInstance(name);
  22277. // Deep copy
  22278. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  22279. // Bounding info
  22280. this.refreshBoundingInfo();
  22281. // Parent
  22282. if (newParent) {
  22283. result.parent = newParent;
  22284. }
  22285. if (!doNotCloneChildren) {
  22286. // Children
  22287. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22288. var mesh = this.getScene().meshes[index];
  22289. if (mesh.parent === this) {
  22290. mesh.clone(mesh.name, result);
  22291. }
  22292. }
  22293. }
  22294. result.computeWorldMatrix(true);
  22295. return result;
  22296. };
  22297. /**
  22298. * Disposes the InstancedMesh.
  22299. * Returns nothing.
  22300. */
  22301. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22302. // Remove from mesh
  22303. var index = this._sourceMesh.instances.indexOf(this);
  22304. this._sourceMesh.instances.splice(index, 1);
  22305. _super.prototype.dispose.call(this, doNotRecurse);
  22306. };
  22307. return InstancedMesh;
  22308. }(BABYLON.AbstractMesh));
  22309. BABYLON.InstancedMesh = InstancedMesh;
  22310. })(BABYLON || (BABYLON = {}));
  22311. //# sourceMappingURL=babylon.instancedMesh.js.map
  22312. var BABYLON;
  22313. (function (BABYLON) {
  22314. var _InstancesBatch = (function () {
  22315. function _InstancesBatch() {
  22316. this.mustReturn = false;
  22317. this.visibleInstances = new Array();
  22318. this.renderSelf = new Array();
  22319. }
  22320. return _InstancesBatch;
  22321. }());
  22322. BABYLON._InstancesBatch = _InstancesBatch;
  22323. var Mesh = (function (_super) {
  22324. __extends(Mesh, _super);
  22325. /**
  22326. * @constructor
  22327. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22328. * @param {Scene} scene The scene to add this mesh to.
  22329. * @param {Node} parent The parent of this mesh, if it has one
  22330. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22331. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22332. * When false, achieved by calling a clone(), also passing False.
  22333. * This will make creation of children, recursive.
  22334. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22335. */
  22336. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22337. if (parent === void 0) { parent = null; }
  22338. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22339. var _this = _super.call(this, name, scene) || this;
  22340. // Events
  22341. /**
  22342. * An event triggered before rendering the mesh
  22343. * @type {BABYLON.Observable}
  22344. */
  22345. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22346. /**
  22347. * An event triggered after rendering the mesh
  22348. * @type {BABYLON.Observable}
  22349. */
  22350. _this.onAfterRenderObservable = new BABYLON.Observable();
  22351. /**
  22352. * An event triggered before drawing the mesh
  22353. * @type {BABYLON.Observable}
  22354. */
  22355. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22356. // Members
  22357. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22358. _this.instances = new Array();
  22359. _this._LODLevels = new Array();
  22360. _this._visibleInstances = {};
  22361. _this._renderIdForInstances = new Array();
  22362. _this._batchCache = new _InstancesBatch();
  22363. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22364. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22365. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22366. // Will be used to save a source mesh reference, If any
  22367. _this._source = null;
  22368. if (source) {
  22369. // Source mesh
  22370. _this._source = source;
  22371. // Geometry
  22372. if (source._geometry) {
  22373. source._geometry.applyToMesh(_this);
  22374. }
  22375. // Deep copy
  22376. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  22377. // Parent
  22378. _this.parent = source.parent;
  22379. // Pivot
  22380. _this.setPivotMatrix(source.getPivotMatrix());
  22381. _this.id = name + "." + source.id;
  22382. // Material
  22383. _this.material = source.material;
  22384. var index;
  22385. if (!doNotCloneChildren) {
  22386. // Children
  22387. for (index = 0; index < scene.meshes.length; index++) {
  22388. var mesh = scene.meshes[index];
  22389. if (mesh.parent === source) {
  22390. // doNotCloneChildren is always going to be False
  22391. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22392. }
  22393. }
  22394. }
  22395. // Physics clone
  22396. var physicsEngine = _this.getScene().getPhysicsEngine();
  22397. if (clonePhysicsImpostor && physicsEngine) {
  22398. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22399. if (impostor) {
  22400. _this.physicsImpostor = impostor.clone(_this);
  22401. }
  22402. }
  22403. // Particles
  22404. for (index = 0; index < scene.particleSystems.length; index++) {
  22405. var system = scene.particleSystems[index];
  22406. if (system.emitter === source) {
  22407. system.clone(system.name, _this);
  22408. }
  22409. }
  22410. _this.computeWorldMatrix(true);
  22411. }
  22412. // Parent
  22413. if (parent !== null) {
  22414. _this.parent = parent;
  22415. }
  22416. return _this;
  22417. }
  22418. Object.defineProperty(Mesh, "FRONTSIDE", {
  22419. /**
  22420. * Mesh side orientation : usually the external or front surface
  22421. */
  22422. get: function () {
  22423. return Mesh._FRONTSIDE;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. Object.defineProperty(Mesh, "BACKSIDE", {
  22429. /**
  22430. * Mesh side orientation : usually the internal or back surface
  22431. */
  22432. get: function () {
  22433. return Mesh._BACKSIDE;
  22434. },
  22435. enumerable: true,
  22436. configurable: true
  22437. });
  22438. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22439. /**
  22440. * Mesh side orientation : both internal and external or front and back surfaces
  22441. */
  22442. get: function () {
  22443. return Mesh._DOUBLESIDE;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22449. /**
  22450. * Mesh side orientation : by default, `FRONTSIDE`
  22451. */
  22452. get: function () {
  22453. return Mesh._DEFAULTSIDE;
  22454. },
  22455. enumerable: true,
  22456. configurable: true
  22457. });
  22458. Object.defineProperty(Mesh, "NO_CAP", {
  22459. /**
  22460. * Mesh cap setting : no cap
  22461. */
  22462. get: function () {
  22463. return Mesh._NO_CAP;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Object.defineProperty(Mesh, "CAP_START", {
  22469. /**
  22470. * Mesh cap setting : one cap at the beginning of the mesh
  22471. */
  22472. get: function () {
  22473. return Mesh._CAP_START;
  22474. },
  22475. enumerable: true,
  22476. configurable: true
  22477. });
  22478. Object.defineProperty(Mesh, "CAP_END", {
  22479. /**
  22480. * Mesh cap setting : one cap at the end of the mesh
  22481. */
  22482. get: function () {
  22483. return Mesh._CAP_END;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(Mesh, "CAP_ALL", {
  22489. /**
  22490. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22491. */
  22492. get: function () {
  22493. return Mesh._CAP_ALL;
  22494. },
  22495. enumerable: true,
  22496. configurable: true
  22497. });
  22498. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22499. set: function (callback) {
  22500. if (this._onBeforeDrawObserver) {
  22501. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22502. }
  22503. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. Object.defineProperty(Mesh.prototype, "source", {
  22509. get: function () {
  22510. return this._source;
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. // Methods
  22516. /**
  22517. * Returns the string "Mesh".
  22518. */
  22519. Mesh.prototype.getClassName = function () {
  22520. return "Mesh";
  22521. };
  22522. /**
  22523. * Returns a string.
  22524. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22525. */
  22526. Mesh.prototype.toString = function (fullDetails) {
  22527. var ret = _super.prototype.toString.call(this, fullDetails);
  22528. ret += ", n vertices: " + this.getTotalVertices();
  22529. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22530. if (this.animations) {
  22531. for (var i = 0; i < this.animations.length; i++) {
  22532. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22533. }
  22534. }
  22535. if (fullDetails) {
  22536. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  22537. }
  22538. return ret;
  22539. };
  22540. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22541. /**
  22542. * True if the mesh has some Levels Of Details (LOD).
  22543. * Returns a boolean.
  22544. */
  22545. get: function () {
  22546. return this._LODLevels.length > 0;
  22547. },
  22548. enumerable: true,
  22549. configurable: true
  22550. });
  22551. Mesh.prototype._sortLODLevels = function () {
  22552. this._LODLevels.sort(function (a, b) {
  22553. if (a.distance < b.distance) {
  22554. return 1;
  22555. }
  22556. if (a.distance > b.distance) {
  22557. return -1;
  22558. }
  22559. return 0;
  22560. });
  22561. };
  22562. /**
  22563. * Add a mesh as LOD level triggered at the given distance.
  22564. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22565. * @param {number} distance The distance from the center of the object to show this level
  22566. * @param {Mesh} mesh The mesh to be added as LOD level
  22567. * @return {Mesh} This mesh (for chaining)
  22568. */
  22569. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22570. if (mesh && mesh._masterMesh) {
  22571. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22572. return this;
  22573. }
  22574. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22575. this._LODLevels.push(level);
  22576. if (mesh) {
  22577. mesh._masterMesh = this;
  22578. }
  22579. this._sortLODLevels();
  22580. return this;
  22581. };
  22582. /**
  22583. * Returns the LOD level mesh at the passed distance or null if not found.
  22584. * It is related to the method `addLODLevel(distance, mesh)`.
  22585. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22586. * Returns an object Mesh or `null`.
  22587. */
  22588. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22589. for (var index = 0; index < this._LODLevels.length; index++) {
  22590. var level = this._LODLevels[index];
  22591. if (level.distance === distance) {
  22592. return level.mesh;
  22593. }
  22594. }
  22595. return null;
  22596. };
  22597. /**
  22598. * Remove a mesh from the LOD array
  22599. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22600. * @param {Mesh} mesh The mesh to be removed.
  22601. * @return {Mesh} This mesh (for chaining)
  22602. */
  22603. Mesh.prototype.removeLODLevel = function (mesh) {
  22604. for (var index = 0; index < this._LODLevels.length; index++) {
  22605. if (this._LODLevels[index].mesh === mesh) {
  22606. this._LODLevels.splice(index, 1);
  22607. if (mesh) {
  22608. mesh._masterMesh = null;
  22609. }
  22610. }
  22611. }
  22612. this._sortLODLevels();
  22613. return this;
  22614. };
  22615. /**
  22616. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22617. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22618. */
  22619. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22620. if (!this._LODLevels || this._LODLevels.length === 0) {
  22621. return this;
  22622. }
  22623. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  22624. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22625. if (this.onLODLevelSelection) {
  22626. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22627. }
  22628. return this;
  22629. }
  22630. for (var index = 0; index < this._LODLevels.length; index++) {
  22631. var level = this._LODLevels[index];
  22632. if (level.distance < distanceToCamera) {
  22633. if (level.mesh) {
  22634. level.mesh._preActivate();
  22635. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22636. }
  22637. if (this.onLODLevelSelection) {
  22638. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22639. }
  22640. return level.mesh;
  22641. }
  22642. }
  22643. if (this.onLODLevelSelection) {
  22644. this.onLODLevelSelection(distanceToCamera, this, this);
  22645. }
  22646. return this;
  22647. };
  22648. Object.defineProperty(Mesh.prototype, "geometry", {
  22649. /**
  22650. * Returns the mesh internal Geometry object.
  22651. */
  22652. get: function () {
  22653. return this._geometry;
  22654. },
  22655. enumerable: true,
  22656. configurable: true
  22657. });
  22658. /**
  22659. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22660. */
  22661. Mesh.prototype.getTotalVertices = function () {
  22662. if (!this._geometry) {
  22663. return 0;
  22664. }
  22665. return this._geometry.getTotalVertices();
  22666. };
  22667. /**
  22668. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22669. * 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.
  22670. * Returns null if the mesh has no geometry or no vertex buffer.
  22671. * Possible `kind` values :
  22672. * - BABYLON.VertexBuffer.PositionKind
  22673. * - BABYLON.VertexBuffer.UVKind
  22674. * - BABYLON.VertexBuffer.UV2Kind
  22675. * - BABYLON.VertexBuffer.UV3Kind
  22676. * - BABYLON.VertexBuffer.UV4Kind
  22677. * - BABYLON.VertexBuffer.UV5Kind
  22678. * - BABYLON.VertexBuffer.UV6Kind
  22679. * - BABYLON.VertexBuffer.ColorKind
  22680. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22681. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22682. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22683. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22684. */
  22685. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22686. if (!this._geometry) {
  22687. return null;
  22688. }
  22689. return this._geometry.getVerticesData(kind, copyWhenShared);
  22690. };
  22691. /**
  22692. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22693. * Returns `undefined` if the mesh has no geometry.
  22694. * Possible `kind` values :
  22695. * - BABYLON.VertexBuffer.PositionKind
  22696. * - BABYLON.VertexBuffer.UVKind
  22697. * - BABYLON.VertexBuffer.UV2Kind
  22698. * - BABYLON.VertexBuffer.UV3Kind
  22699. * - BABYLON.VertexBuffer.UV4Kind
  22700. * - BABYLON.VertexBuffer.UV5Kind
  22701. * - BABYLON.VertexBuffer.UV6Kind
  22702. * - BABYLON.VertexBuffer.ColorKind
  22703. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22704. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22705. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22706. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22707. */
  22708. Mesh.prototype.getVertexBuffer = function (kind) {
  22709. if (!this._geometry) {
  22710. return undefined;
  22711. }
  22712. return this._geometry.getVertexBuffer(kind);
  22713. };
  22714. /**
  22715. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22716. * Possible `kind` values :
  22717. * - BABYLON.VertexBuffer.PositionKind
  22718. * - BABYLON.VertexBuffer.UVKind
  22719. * - BABYLON.VertexBuffer.UV2Kind
  22720. * - BABYLON.VertexBuffer.UV3Kind
  22721. * - BABYLON.VertexBuffer.UV4Kind
  22722. * - BABYLON.VertexBuffer.UV5Kind
  22723. * - BABYLON.VertexBuffer.UV6Kind
  22724. * - BABYLON.VertexBuffer.ColorKind
  22725. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22726. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22727. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22728. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22729. */
  22730. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22731. if (!this._geometry) {
  22732. if (this._delayInfo) {
  22733. return this._delayInfo.indexOf(kind) !== -1;
  22734. }
  22735. return false;
  22736. }
  22737. return this._geometry.isVerticesDataPresent(kind);
  22738. };
  22739. /**
  22740. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22741. * Possible `kind` values :
  22742. * - BABYLON.VertexBuffer.PositionKind
  22743. * - BABYLON.VertexBuffer.UVKind
  22744. * - BABYLON.VertexBuffer.UV2Kind
  22745. * - BABYLON.VertexBuffer.UV3Kind
  22746. * - BABYLON.VertexBuffer.UV4Kind
  22747. * - BABYLON.VertexBuffer.UV5Kind
  22748. * - BABYLON.VertexBuffer.UV6Kind
  22749. * - BABYLON.VertexBuffer.ColorKind
  22750. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22751. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22752. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22753. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22754. */
  22755. Mesh.prototype.getVerticesDataKinds = function () {
  22756. if (!this._geometry) {
  22757. var result = [];
  22758. if (this._delayInfo) {
  22759. this._delayInfo.forEach(function (kind, index, array) {
  22760. result.push(kind);
  22761. });
  22762. }
  22763. return result;
  22764. }
  22765. return this._geometry.getVerticesDataKinds();
  22766. };
  22767. /**
  22768. * Returns a positive integer : the total number of indices in this mesh geometry.
  22769. * Returns zero if the mesh has no geometry.
  22770. */
  22771. Mesh.prototype.getTotalIndices = function () {
  22772. if (!this._geometry) {
  22773. return 0;
  22774. }
  22775. return this._geometry.getTotalIndices();
  22776. };
  22777. /**
  22778. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22779. * 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.
  22780. * Returns an empty array if the mesh has no geometry.
  22781. */
  22782. Mesh.prototype.getIndices = function (copyWhenShared) {
  22783. if (!this._geometry) {
  22784. return [];
  22785. }
  22786. return this._geometry.getIndices(copyWhenShared);
  22787. };
  22788. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22789. get: function () {
  22790. return this._masterMesh !== null && this._masterMesh !== undefined;
  22791. },
  22792. enumerable: true,
  22793. configurable: true
  22794. });
  22795. /**
  22796. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22797. */
  22798. Mesh.prototype.isReady = function () {
  22799. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22800. return false;
  22801. }
  22802. return _super.prototype.isReady.call(this);
  22803. };
  22804. /**
  22805. * Boolean : true if the mesh has been disposed.
  22806. */
  22807. Mesh.prototype.isDisposed = function () {
  22808. return this._isDisposed;
  22809. };
  22810. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  22811. get: function () {
  22812. return this._sideOrientation;
  22813. },
  22814. /**
  22815. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  22816. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  22817. */
  22818. set: function (sideO) {
  22819. this._sideOrientation = sideO;
  22820. },
  22821. enumerable: true,
  22822. configurable: true
  22823. });
  22824. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22825. /**
  22826. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22827. * This property is pertinent only for updatable parametric shapes.
  22828. */
  22829. get: function () {
  22830. return this._areNormalsFrozen;
  22831. },
  22832. enumerable: true,
  22833. configurable: true
  22834. });
  22835. /**
  22836. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22837. * It has no effect at all on other shapes.
  22838. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22839. * Returns the Mesh.
  22840. */
  22841. Mesh.prototype.freezeNormals = function () {
  22842. this._areNormalsFrozen = true;
  22843. return this;
  22844. };
  22845. /**
  22846. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22847. * It has no effect at all on other shapes.
  22848. * It reactivates the mesh normals computation if it was previously frozen.
  22849. * Returns the Mesh.
  22850. */
  22851. Mesh.prototype.unfreezeNormals = function () {
  22852. this._areNormalsFrozen = false;
  22853. return this;
  22854. };
  22855. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22856. /**
  22857. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22858. */
  22859. set: function (count) {
  22860. this._overridenInstanceCount = count;
  22861. },
  22862. enumerable: true,
  22863. configurable: true
  22864. });
  22865. // Methods
  22866. Mesh.prototype._preActivate = function () {
  22867. var sceneRenderId = this.getScene().getRenderId();
  22868. if (this._preActivateId === sceneRenderId) {
  22869. return this;
  22870. }
  22871. this._preActivateId = sceneRenderId;
  22872. this._visibleInstances = null;
  22873. return this;
  22874. };
  22875. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22876. if (this._visibleInstances) {
  22877. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22878. }
  22879. return this;
  22880. };
  22881. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22882. if (!this._visibleInstances) {
  22883. this._visibleInstances = {};
  22884. this._visibleInstances.defaultRenderId = renderId;
  22885. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22886. }
  22887. if (!this._visibleInstances[renderId]) {
  22888. this._visibleInstances[renderId] = new Array();
  22889. }
  22890. this._visibleInstances[renderId].push(instance);
  22891. return this;
  22892. };
  22893. /**
  22894. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22895. * This means the mesh underlying bounding box and sphere are recomputed.
  22896. * Returns the Mesh.
  22897. */
  22898. Mesh.prototype.refreshBoundingInfo = function () {
  22899. if (this._boundingInfo.isLocked) {
  22900. return;
  22901. }
  22902. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22903. if (data) {
  22904. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22905. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22906. }
  22907. if (this.subMeshes) {
  22908. for (var index = 0; index < this.subMeshes.length; index++) {
  22909. this.subMeshes[index].refreshBoundingInfo();
  22910. }
  22911. }
  22912. this._updateBoundingInfo();
  22913. return this;
  22914. };
  22915. Mesh.prototype._createGlobalSubMesh = function () {
  22916. var totalVertices = this.getTotalVertices();
  22917. if (!totalVertices || !this.getIndices()) {
  22918. return null;
  22919. }
  22920. this.releaseSubMeshes();
  22921. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22922. };
  22923. Mesh.prototype.subdivide = function (count) {
  22924. if (count < 1) {
  22925. return;
  22926. }
  22927. var totalIndices = this.getTotalIndices();
  22928. var subdivisionSize = (totalIndices / count) | 0;
  22929. var offset = 0;
  22930. // Ensure that subdivisionSize is a multiple of 3
  22931. while (subdivisionSize % 3 !== 0) {
  22932. subdivisionSize++;
  22933. }
  22934. this.releaseSubMeshes();
  22935. for (var index = 0; index < count; index++) {
  22936. if (offset >= totalIndices) {
  22937. break;
  22938. }
  22939. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22940. offset += subdivisionSize;
  22941. }
  22942. this.synchronizeInstances();
  22943. };
  22944. /**
  22945. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22946. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22947. * The `data` are either a numeric array either a Float32Array.
  22948. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22949. * 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).
  22950. * Note that a new underlying VertexBuffer object is created each call.
  22951. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22952. *
  22953. * Possible `kind` values :
  22954. * - BABYLON.VertexBuffer.PositionKind
  22955. * - BABYLON.VertexBuffer.UVKind
  22956. * - BABYLON.VertexBuffer.UV2Kind
  22957. * - BABYLON.VertexBuffer.UV3Kind
  22958. * - BABYLON.VertexBuffer.UV4Kind
  22959. * - BABYLON.VertexBuffer.UV5Kind
  22960. * - BABYLON.VertexBuffer.UV6Kind
  22961. * - BABYLON.VertexBuffer.ColorKind
  22962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22966. *
  22967. * Returns the Mesh.
  22968. */
  22969. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22970. if (!this._geometry) {
  22971. var vertexData = new BABYLON.VertexData();
  22972. vertexData.set(data, kind);
  22973. var scene = this.getScene();
  22974. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22975. }
  22976. else {
  22977. this._geometry.setVerticesData(kind, data, updatable, stride);
  22978. }
  22979. return this;
  22980. };
  22981. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22982. if (updatable === void 0) { updatable = true; }
  22983. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22984. return;
  22985. }
  22986. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22987. };
  22988. /**
  22989. * Sets the mesh VertexBuffer.
  22990. * Returns the Mesh.
  22991. */
  22992. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22993. if (!this._geometry) {
  22994. var scene = this.getScene();
  22995. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22996. }
  22997. this._geometry.setVerticesBuffer(buffer);
  22998. return this;
  22999. };
  23000. /**
  23001. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23002. * If the mesh has no geometry, it is simply returned as it is.
  23003. * The `data` are either a numeric array either a Float32Array.
  23004. * No new underlying VertexBuffer object is created.
  23005. * 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.
  23006. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23007. *
  23008. * Possible `kind` values :
  23009. * - BABYLON.VertexBuffer.PositionKind
  23010. * - BABYLON.VertexBuffer.UVKind
  23011. * - BABYLON.VertexBuffer.UV2Kind
  23012. * - BABYLON.VertexBuffer.UV3Kind
  23013. * - BABYLON.VertexBuffer.UV4Kind
  23014. * - BABYLON.VertexBuffer.UV5Kind
  23015. * - BABYLON.VertexBuffer.UV6Kind
  23016. * - BABYLON.VertexBuffer.ColorKind
  23017. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23018. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23019. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23020. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23021. *
  23022. * Returns the Mesh.
  23023. */
  23024. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23025. if (!this._geometry) {
  23026. return;
  23027. }
  23028. if (!makeItUnique) {
  23029. this._geometry.updateVerticesData(kind, data, updateExtends);
  23030. }
  23031. else {
  23032. this.makeGeometryUnique();
  23033. this.updateVerticesData(kind, data, updateExtends, false);
  23034. }
  23035. return this;
  23036. };
  23037. /**
  23038. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23039. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23040. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23041. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23042. * Returns the Mesh.
  23043. */
  23044. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23045. if (computeNormals === void 0) { computeNormals = true; }
  23046. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23047. positionFunction(positions);
  23048. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23049. if (computeNormals) {
  23050. var indices = this.getIndices();
  23051. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23052. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23053. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23054. }
  23055. return this;
  23056. };
  23057. /**
  23058. * Creates a un-shared specific occurence of the geometry for the mesh.
  23059. * Returns the Mesh.
  23060. */
  23061. Mesh.prototype.makeGeometryUnique = function () {
  23062. if (!this._geometry) {
  23063. return;
  23064. }
  23065. var oldGeometry = this._geometry;
  23066. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23067. oldGeometry.releaseForMesh(this, true);
  23068. geometry.applyToMesh(this);
  23069. return this;
  23070. };
  23071. /**
  23072. * Sets the mesh indices.
  23073. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23074. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23075. * This method creates a new index buffer each call.
  23076. * Returns the Mesh.
  23077. */
  23078. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23079. if (!this._geometry) {
  23080. var vertexData = new BABYLON.VertexData();
  23081. vertexData.indices = indices;
  23082. var scene = this.getScene();
  23083. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23084. }
  23085. else {
  23086. this._geometry.setIndices(indices, totalVertices);
  23087. }
  23088. return this;
  23089. };
  23090. /**
  23091. * Invert the geometry to move from a right handed system to a left handed one.
  23092. * Returns the Mesh.
  23093. */
  23094. Mesh.prototype.toLeftHanded = function () {
  23095. if (!this._geometry) {
  23096. return;
  23097. }
  23098. this._geometry.toLeftHanded();
  23099. return this;
  23100. };
  23101. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23102. var engine = this.getScene().getEngine();
  23103. // Wireframe
  23104. var indexToBind;
  23105. if (this._unIndexed) {
  23106. indexToBind = null;
  23107. }
  23108. else {
  23109. switch (fillMode) {
  23110. case BABYLON.Material.PointFillMode:
  23111. indexToBind = null;
  23112. break;
  23113. case BABYLON.Material.WireFrameFillMode:
  23114. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23115. break;
  23116. default:
  23117. case BABYLON.Material.TriangleFillMode:
  23118. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23119. break;
  23120. }
  23121. }
  23122. // VBOs
  23123. this._geometry._bind(effect, indexToBind);
  23124. return this;
  23125. };
  23126. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23127. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23128. return this;
  23129. }
  23130. this.onBeforeDrawObservable.notifyObservers(this);
  23131. var engine = this.getScene().getEngine();
  23132. // Draw order
  23133. switch (fillMode) {
  23134. case BABYLON.Material.PointFillMode:
  23135. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23136. break;
  23137. case BABYLON.Material.WireFrameFillMode:
  23138. if (this._unIndexed) {
  23139. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23140. }
  23141. else {
  23142. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23143. }
  23144. break;
  23145. default:
  23146. if (this._unIndexed) {
  23147. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23148. }
  23149. else {
  23150. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23151. }
  23152. }
  23153. return this;
  23154. };
  23155. /**
  23156. * Registers for this mesh a javascript function called just before the rendering process.
  23157. * This function is passed the current mesh.
  23158. * Return the Mesh.
  23159. */
  23160. Mesh.prototype.registerBeforeRender = function (func) {
  23161. this.onBeforeRenderObservable.add(func);
  23162. return this;
  23163. };
  23164. /**
  23165. * Disposes a previously registered javascript function called before the rendering.
  23166. * This function is passed the current mesh.
  23167. * Returns the Mesh.
  23168. */
  23169. Mesh.prototype.unregisterBeforeRender = function (func) {
  23170. this.onBeforeRenderObservable.removeCallback(func);
  23171. return this;
  23172. };
  23173. /**
  23174. * Registers for this mesh a javascript function called just after the rendering is complete.
  23175. * This function is passed the current mesh.
  23176. * Returns the Mesh.
  23177. */
  23178. Mesh.prototype.registerAfterRender = function (func) {
  23179. this.onAfterRenderObservable.add(func);
  23180. return this;
  23181. };
  23182. /**
  23183. * Disposes a previously registered javascript function called after the rendering.
  23184. * This function is passed the current mesh.
  23185. * Return the Mesh.
  23186. */
  23187. Mesh.prototype.unregisterAfterRender = function (func) {
  23188. this.onAfterRenderObservable.removeCallback(func);
  23189. return this;
  23190. };
  23191. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23192. var scene = this.getScene();
  23193. this._batchCache.mustReturn = false;
  23194. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23195. this._batchCache.visibleInstances[subMeshId] = null;
  23196. if (this._visibleInstances) {
  23197. var currentRenderId = scene.getRenderId();
  23198. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23199. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23200. var selfRenderId = this._renderId;
  23201. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23202. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23203. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23204. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23205. }
  23206. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23207. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23208. this._batchCache.mustReturn = true;
  23209. return this._batchCache;
  23210. }
  23211. if (currentRenderId !== selfRenderId) {
  23212. this._batchCache.renderSelf[subMeshId] = false;
  23213. }
  23214. }
  23215. this._renderIdForInstances[subMeshId] = currentRenderId;
  23216. }
  23217. return this._batchCache;
  23218. };
  23219. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23220. var visibleInstances = batch.visibleInstances[subMesh._id];
  23221. var matricesCount = visibleInstances.length + 1;
  23222. var bufferSize = matricesCount * 16 * 4;
  23223. var currentInstancesBufferSize = this._instancesBufferSize;
  23224. var instancesBuffer = this._instancesBuffer;
  23225. while (this._instancesBufferSize < bufferSize) {
  23226. this._instancesBufferSize *= 2;
  23227. }
  23228. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23229. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23230. }
  23231. var offset = 0;
  23232. var instancesCount = 0;
  23233. var world = this.getWorldMatrix();
  23234. if (batch.renderSelf[subMesh._id]) {
  23235. world.copyToArray(this._instancesData, offset);
  23236. offset += 16;
  23237. instancesCount++;
  23238. }
  23239. if (visibleInstances) {
  23240. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23241. var instance = visibleInstances[instanceIndex];
  23242. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23243. offset += 16;
  23244. instancesCount++;
  23245. }
  23246. }
  23247. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23248. if (instancesBuffer) {
  23249. instancesBuffer.dispose();
  23250. }
  23251. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23252. this._instancesBuffer = instancesBuffer;
  23253. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23254. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23255. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23256. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23257. }
  23258. else {
  23259. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23260. }
  23261. this.geometry._bind(effect);
  23262. this._draw(subMesh, fillMode, instancesCount);
  23263. engine.unbindInstanceAttributes();
  23264. return this;
  23265. };
  23266. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23267. var scene = this.getScene();
  23268. var engine = scene.getEngine();
  23269. if (hardwareInstancedRendering) {
  23270. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23271. }
  23272. else {
  23273. if (batch.renderSelf[subMesh._id]) {
  23274. // Draw
  23275. if (onBeforeDraw) {
  23276. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23277. }
  23278. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23279. }
  23280. if (batch.visibleInstances[subMesh._id]) {
  23281. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23282. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23283. // World
  23284. var world = instance.getWorldMatrix();
  23285. if (onBeforeDraw) {
  23286. onBeforeDraw(true, world, effectiveMaterial);
  23287. }
  23288. // Draw
  23289. this._draw(subMesh, fillMode);
  23290. }
  23291. }
  23292. }
  23293. return this;
  23294. };
  23295. /**
  23296. * Triggers the draw call for the mesh.
  23297. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23298. * Returns the Mesh.
  23299. */
  23300. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23301. var scene = this.getScene();
  23302. // Managing instances
  23303. var batch = this._getInstancesRenderList(subMesh._id);
  23304. if (batch.mustReturn) {
  23305. return this;
  23306. }
  23307. // Checking geometry state
  23308. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23309. return this;
  23310. }
  23311. var callbackIndex;
  23312. this.onBeforeRenderObservable.notifyObservers(this);
  23313. var engine = scene.getEngine();
  23314. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23315. // Material
  23316. var effectiveMaterial = subMesh.getMaterial();
  23317. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23318. return this;
  23319. }
  23320. // Outline - step 1
  23321. var savedDepthWrite = engine.getDepthWrite();
  23322. if (this.renderOutline) {
  23323. engine.setDepthWrite(false);
  23324. scene.getOutlineRenderer().render(subMesh, batch);
  23325. engine.setDepthWrite(savedDepthWrite);
  23326. }
  23327. effectiveMaterial._preBind();
  23328. var effect = effectiveMaterial.getEffect();
  23329. // Bind
  23330. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23331. this._bind(subMesh, effect, fillMode);
  23332. var world = this.getWorldMatrix();
  23333. effectiveMaterial.bind(world, this);
  23334. // Alpha mode
  23335. if (enableAlphaMode) {
  23336. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23337. }
  23338. // Draw
  23339. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23340. // Unbind
  23341. effectiveMaterial.unbind();
  23342. // Outline - step 2
  23343. if (this.renderOutline && savedDepthWrite) {
  23344. engine.setDepthWrite(true);
  23345. engine.setColorWrite(false);
  23346. scene.getOutlineRenderer().render(subMesh, batch);
  23347. engine.setColorWrite(true);
  23348. }
  23349. // Overlay
  23350. if (this.renderOverlay) {
  23351. var currentMode = engine.getAlphaMode();
  23352. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23353. scene.getOutlineRenderer().render(subMesh, batch, true);
  23354. engine.setAlphaMode(currentMode);
  23355. }
  23356. this.onAfterRenderObservable.notifyObservers(this);
  23357. return this;
  23358. };
  23359. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23360. if (isInstance) {
  23361. effectiveMaterial.bindOnlyWorldMatrix(world);
  23362. }
  23363. return this;
  23364. };
  23365. /**
  23366. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23367. */
  23368. Mesh.prototype.getEmittedParticleSystems = function () {
  23369. var results = new Array();
  23370. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23371. var particleSystem = this.getScene().particleSystems[index];
  23372. if (particleSystem.emitter === this) {
  23373. results.push(particleSystem);
  23374. }
  23375. }
  23376. return results;
  23377. };
  23378. /**
  23379. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23380. */
  23381. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23382. var results = new Array();
  23383. var descendants = this.getDescendants();
  23384. descendants.push(this);
  23385. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23386. var particleSystem = this.getScene().particleSystems[index];
  23387. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23388. results.push(particleSystem);
  23389. }
  23390. }
  23391. return results;
  23392. };
  23393. Mesh.prototype._checkDelayState = function () {
  23394. var scene = this.getScene();
  23395. if (this._geometry) {
  23396. this._geometry.load(scene);
  23397. }
  23398. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23399. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23400. this._queueLoad(this, scene);
  23401. }
  23402. return this;
  23403. };
  23404. Mesh.prototype._queueLoad = function (mesh, scene) {
  23405. var _this = this;
  23406. scene._addPendingData(mesh);
  23407. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23408. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23409. if (data instanceof ArrayBuffer) {
  23410. _this._delayLoadingFunction(data, _this);
  23411. }
  23412. else {
  23413. _this._delayLoadingFunction(JSON.parse(data), _this);
  23414. }
  23415. _this.instances.forEach(function (instance) {
  23416. instance._syncSubMeshes();
  23417. });
  23418. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23419. scene._removePendingData(_this);
  23420. }, function () { }, scene.database, getBinaryData);
  23421. return this;
  23422. };
  23423. /**
  23424. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23425. */
  23426. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23427. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23428. return false;
  23429. }
  23430. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23431. return false;
  23432. }
  23433. this._checkDelayState();
  23434. return true;
  23435. };
  23436. /**
  23437. * Sets the mesh material by the material or multiMaterial `id` property.
  23438. * The material `id` is a string identifying the material or the multiMaterial.
  23439. * This method returns the Mesh.
  23440. */
  23441. Mesh.prototype.setMaterialByID = function (id) {
  23442. var materials = this.getScene().materials;
  23443. var index;
  23444. for (index = 0; index < materials.length; index++) {
  23445. if (materials[index].id === id) {
  23446. this.material = materials[index];
  23447. return this;
  23448. }
  23449. }
  23450. // Multi
  23451. var multiMaterials = this.getScene().multiMaterials;
  23452. for (index = 0; index < multiMaterials.length; index++) {
  23453. if (multiMaterials[index].id === id) {
  23454. this.material = multiMaterials[index];
  23455. return this;
  23456. }
  23457. }
  23458. return this;
  23459. };
  23460. /**
  23461. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23462. */
  23463. Mesh.prototype.getAnimatables = function () {
  23464. var results = [];
  23465. if (this.material) {
  23466. results.push(this.material);
  23467. }
  23468. if (this.skeleton) {
  23469. results.push(this.skeleton);
  23470. }
  23471. return results;
  23472. };
  23473. /**
  23474. * Modifies the mesh geometry according to the passed transformation matrix.
  23475. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23476. * The mesh normals are modified accordingly the same transformation.
  23477. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23478. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23479. * Returns the Mesh.
  23480. */
  23481. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23482. // Position
  23483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23484. return this;
  23485. }
  23486. var submeshes = this.subMeshes.splice(0);
  23487. this._resetPointsArrayCache();
  23488. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23489. var temp = [];
  23490. var index;
  23491. for (index = 0; index < data.length; index += 3) {
  23492. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23493. }
  23494. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23495. // Normals
  23496. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23497. return this;
  23498. }
  23499. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23500. temp = [];
  23501. for (index = 0; index < data.length; index += 3) {
  23502. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23503. }
  23504. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23505. // flip faces?
  23506. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23507. this.flipFaces();
  23508. }
  23509. // Restore submeshes
  23510. this.releaseSubMeshes();
  23511. this.subMeshes = submeshes;
  23512. return this;
  23513. };
  23514. /**
  23515. * Modifies the mesh geometry according to its own current World Matrix.
  23516. * The mesh World Matrix is then reset.
  23517. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23518. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23519. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23520. * Returns the Mesh.
  23521. */
  23522. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23523. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23524. this.scaling.copyFromFloats(1, 1, 1);
  23525. this.position.copyFromFloats(0, 0, 0);
  23526. this.rotation.copyFromFloats(0, 0, 0);
  23527. //only if quaternion is already set
  23528. if (this.rotationQuaternion) {
  23529. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23530. }
  23531. this._worldMatrix = BABYLON.Matrix.Identity();
  23532. return this;
  23533. };
  23534. // Cache
  23535. Mesh.prototype._resetPointsArrayCache = function () {
  23536. this._positions = null;
  23537. return this;
  23538. };
  23539. Mesh.prototype._generatePointsArray = function () {
  23540. if (this._positions)
  23541. return true;
  23542. this._positions = [];
  23543. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23544. if (!data) {
  23545. return false;
  23546. }
  23547. for (var index = 0; index < data.length; index += 3) {
  23548. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  23549. }
  23550. return true;
  23551. };
  23552. /**
  23553. * Returns a new Mesh object generated from the current mesh properties.
  23554. * This method must not get confused with createInstance().
  23555. * The parameter `name` is a string, the name given to the new mesh.
  23556. * The optional parameter `newParent` can be any Node object (default `null`).
  23557. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23558. * 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.
  23559. */
  23560. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23561. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23562. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23563. };
  23564. /**
  23565. * Disposes the mesh.
  23566. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23567. */
  23568. Mesh.prototype.dispose = function (doNotRecurse) {
  23569. var _this = this;
  23570. if (this._geometry) {
  23571. this._geometry.releaseForMesh(this, true);
  23572. }
  23573. // Sources
  23574. var meshes = this.getScene().meshes;
  23575. meshes.forEach(function (mesh) {
  23576. if (mesh._source && mesh._source === _this) {
  23577. mesh._source = null;
  23578. }
  23579. });
  23580. this._source = null;
  23581. // Instances
  23582. if (this._instancesBuffer) {
  23583. this._instancesBuffer.dispose();
  23584. this._instancesBuffer = null;
  23585. }
  23586. while (this.instances.length) {
  23587. this.instances[0].dispose();
  23588. }
  23589. // Highlight layers.
  23590. var highlightLayers = this.getScene().highlightLayers;
  23591. for (var i = 0; i < highlightLayers.length; i++) {
  23592. var highlightLayer = highlightLayers[i];
  23593. if (highlightLayer) {
  23594. highlightLayer.removeMesh(this);
  23595. highlightLayer.removeExcludedMesh(this);
  23596. }
  23597. }
  23598. _super.prototype.dispose.call(this, doNotRecurse);
  23599. };
  23600. /**
  23601. * Modifies the mesh geometry according to a displacement map.
  23602. * 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.
  23603. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23604. * This method returns nothing.
  23605. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23606. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23607. * 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.
  23608. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23609. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23610. *
  23611. * Returns the Mesh.
  23612. */
  23613. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23614. var _this = this;
  23615. var scene = this.getScene();
  23616. var onload = function (img) {
  23617. // Getting height map data
  23618. var canvas = document.createElement("canvas");
  23619. var context = canvas.getContext("2d");
  23620. var heightMapWidth = img.width;
  23621. var heightMapHeight = img.height;
  23622. canvas.width = heightMapWidth;
  23623. canvas.height = heightMapHeight;
  23624. context.drawImage(img, 0, 0);
  23625. // Create VertexData from map data
  23626. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23627. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23628. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23629. //execute success callback, if set
  23630. if (onSuccess) {
  23631. onSuccess(_this);
  23632. }
  23633. };
  23634. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23635. return this;
  23636. };
  23637. /**
  23638. * Modifies the mesh geometry according to a displacementMap buffer.
  23639. * 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.
  23640. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23641. * This method returns nothing.
  23642. * 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.
  23643. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23644. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23645. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23646. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23647. *
  23648. * Returns the Mesh.
  23649. */
  23650. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23652. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23653. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23654. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23655. return this;
  23656. }
  23657. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23658. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23659. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23660. var position = BABYLON.Vector3.Zero();
  23661. var normal = BABYLON.Vector3.Zero();
  23662. var uv = BABYLON.Vector2.Zero();
  23663. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23664. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23665. for (var index = 0; index < positions.length; index += 3) {
  23666. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23667. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23668. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23669. // Compute height
  23670. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23671. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23672. var pos = (u + v * heightMapWidth) * 4;
  23673. var r = buffer[pos] / 255.0;
  23674. var g = buffer[pos + 1] / 255.0;
  23675. var b = buffer[pos + 2] / 255.0;
  23676. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23677. normal.normalize();
  23678. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23679. position = position.add(normal);
  23680. position.toArray(positions, index);
  23681. }
  23682. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23683. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23684. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23685. return this;
  23686. };
  23687. /**
  23688. * Modify the mesh to get a flat shading rendering.
  23689. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23690. * This method returns the Mesh.
  23691. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23692. */
  23693. Mesh.prototype.convertToFlatShadedMesh = function () {
  23694. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23695. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23696. var kinds = this.getVerticesDataKinds();
  23697. var vbs = [];
  23698. var data = [];
  23699. var newdata = [];
  23700. var updatableNormals = false;
  23701. var kindIndex;
  23702. var kind;
  23703. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23704. kind = kinds[kindIndex];
  23705. var vertexBuffer = this.getVertexBuffer(kind);
  23706. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23707. updatableNormals = vertexBuffer.isUpdatable();
  23708. kinds.splice(kindIndex, 1);
  23709. kindIndex--;
  23710. continue;
  23711. }
  23712. vbs[kind] = vertexBuffer;
  23713. data[kind] = vbs[kind].getData();
  23714. newdata[kind] = [];
  23715. }
  23716. // Save previous submeshes
  23717. var previousSubmeshes = this.subMeshes.slice(0);
  23718. var indices = this.getIndices();
  23719. var totalIndices = this.getTotalIndices();
  23720. // Generating unique vertices per face
  23721. var index;
  23722. for (index = 0; index < totalIndices; index++) {
  23723. var vertexIndex = indices[index];
  23724. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23725. kind = kinds[kindIndex];
  23726. var stride = vbs[kind].getStrideSize();
  23727. for (var offset = 0; offset < stride; offset++) {
  23728. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23729. }
  23730. }
  23731. }
  23732. // Updating faces & normal
  23733. var normals = [];
  23734. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23735. for (index = 0; index < totalIndices; index += 3) {
  23736. indices[index] = index;
  23737. indices[index + 1] = index + 1;
  23738. indices[index + 2] = index + 2;
  23739. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23740. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23741. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23742. var p1p2 = p1.subtract(p2);
  23743. var p3p2 = p3.subtract(p2);
  23744. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23745. // Store same normals for every vertex
  23746. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23747. normals.push(normal.x);
  23748. normals.push(normal.y);
  23749. normals.push(normal.z);
  23750. }
  23751. }
  23752. this.setIndices(indices);
  23753. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23754. // Updating vertex buffers
  23755. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23756. kind = kinds[kindIndex];
  23757. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23758. }
  23759. // Updating submeshes
  23760. this.releaseSubMeshes();
  23761. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23762. var previousOne = previousSubmeshes[submeshIndex];
  23763. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23764. }
  23765. this.synchronizeInstances();
  23766. return this;
  23767. };
  23768. /**
  23769. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  23770. * In other words, more vertices, no more indices and a single bigger VBO.
  23771. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  23772. * Returns the Mesh.
  23773. */
  23774. Mesh.prototype.convertToUnIndexedMesh = function () {
  23775. /// <summary>Remove indices by unfolding faces into buffers</summary>
  23776. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23777. var kinds = this.getVerticesDataKinds();
  23778. var vbs = [];
  23779. var data = [];
  23780. var newdata = [];
  23781. var updatableNormals = false;
  23782. var kindIndex;
  23783. var kind;
  23784. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23785. kind = kinds[kindIndex];
  23786. var vertexBuffer = this.getVertexBuffer(kind);
  23787. vbs[kind] = vertexBuffer;
  23788. data[kind] = vbs[kind].getData();
  23789. newdata[kind] = [];
  23790. }
  23791. // Save previous submeshes
  23792. var previousSubmeshes = this.subMeshes.slice(0);
  23793. var indices = this.getIndices();
  23794. var totalIndices = this.getTotalIndices();
  23795. // Generating unique vertices per face
  23796. var index;
  23797. for (index = 0; index < totalIndices; index++) {
  23798. var vertexIndex = indices[index];
  23799. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23800. kind = kinds[kindIndex];
  23801. var stride = vbs[kind].getStrideSize();
  23802. for (var offset = 0; offset < stride; offset++) {
  23803. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23804. }
  23805. }
  23806. }
  23807. // Updating indices
  23808. for (index = 0; index < totalIndices; index += 3) {
  23809. indices[index] = index;
  23810. indices[index + 1] = index + 1;
  23811. indices[index + 2] = index + 2;
  23812. }
  23813. this.setIndices(indices);
  23814. // Updating vertex buffers
  23815. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23816. kind = kinds[kindIndex];
  23817. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23818. }
  23819. // Updating submeshes
  23820. this.releaseSubMeshes();
  23821. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23822. var previousOne = previousSubmeshes[submeshIndex];
  23823. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23824. }
  23825. this._unIndexed = true;
  23826. this.synchronizeInstances();
  23827. return this;
  23828. };
  23829. /**
  23830. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23831. * This method returns the Mesh.
  23832. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23833. */
  23834. Mesh.prototype.flipFaces = function (flipNormals) {
  23835. if (flipNormals === void 0) { flipNormals = false; }
  23836. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23837. var i;
  23838. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23839. for (i = 0; i < vertex_data.normals.length; i++) {
  23840. vertex_data.normals[i] *= -1;
  23841. }
  23842. }
  23843. var temp;
  23844. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23845. // reassign indices
  23846. temp = vertex_data.indices[i + 1];
  23847. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23848. vertex_data.indices[i + 2] = temp;
  23849. }
  23850. vertex_data.applyToMesh(this);
  23851. return this;
  23852. };
  23853. // Instances
  23854. /**
  23855. * Creates a new InstancedMesh object from the mesh model.
  23856. * An instance shares the same properties and the same material than its model.
  23857. * Only these properties of each instance can then be set individually :
  23858. * - position
  23859. * - rotation
  23860. * - rotationQuaternion
  23861. * - setPivotMatrix
  23862. * - scaling
  23863. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23864. * Warning : this method is not supported for Line mesh and LineSystem
  23865. */
  23866. Mesh.prototype.createInstance = function (name) {
  23867. return new BABYLON.InstancedMesh(name, this);
  23868. };
  23869. /**
  23870. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23871. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23872. * This method returns the Mesh.
  23873. */
  23874. Mesh.prototype.synchronizeInstances = function () {
  23875. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23876. var instance = this.instances[instanceIndex];
  23877. instance._syncSubMeshes();
  23878. }
  23879. return this;
  23880. };
  23881. /**
  23882. * Simplify the mesh according to the given array of settings.
  23883. * Function will return immediately and will simplify async. It returns the Mesh.
  23884. * @param settings a collection of simplification settings.
  23885. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23886. * @param type the type of simplification to run.
  23887. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23888. */
  23889. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23890. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23891. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23892. this.getScene().simplificationQueue.addTask({
  23893. settings: settings,
  23894. parallelProcessing: parallelProcessing,
  23895. mesh: this,
  23896. simplificationType: simplificationType,
  23897. successCallback: successCallback
  23898. });
  23899. return this;
  23900. };
  23901. /**
  23902. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23903. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23904. * This should be used together with the simplification to avoid disappearing triangles.
  23905. * Returns the Mesh.
  23906. * @param successCallback an optional success callback to be called after the optimization finished.
  23907. */
  23908. Mesh.prototype.optimizeIndices = function (successCallback) {
  23909. var _this = this;
  23910. var indices = this.getIndices();
  23911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23912. var vectorPositions = [];
  23913. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23914. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23915. }
  23916. var dupes = [];
  23917. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23918. var realPos = vectorPositions.length - 1 - iteration;
  23919. var testedPosition = vectorPositions[realPos];
  23920. for (var j = 0; j < realPos; ++j) {
  23921. var againstPosition = vectorPositions[j];
  23922. if (testedPosition.equals(againstPosition)) {
  23923. dupes[realPos] = j;
  23924. break;
  23925. }
  23926. }
  23927. }, function () {
  23928. for (var i = 0; i < indices.length; ++i) {
  23929. indices[i] = dupes[indices[i]] || indices[i];
  23930. }
  23931. //indices are now reordered
  23932. var originalSubMeshes = _this.subMeshes.slice(0);
  23933. _this.setIndices(indices);
  23934. _this.subMeshes = originalSubMeshes;
  23935. if (successCallback) {
  23936. successCallback(_this);
  23937. }
  23938. });
  23939. return this;
  23940. };
  23941. Mesh.prototype.serialize = function (serializationObject) {
  23942. serializationObject.name = this.name;
  23943. serializationObject.id = this.id;
  23944. serializationObject.type = this.getClassName();
  23945. if (BABYLON.Tags.HasTags(this)) {
  23946. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23947. }
  23948. serializationObject.position = this.position.asArray();
  23949. if (this.rotationQuaternion) {
  23950. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23951. }
  23952. else if (this.rotation) {
  23953. serializationObject.rotation = this.rotation.asArray();
  23954. }
  23955. serializationObject.scaling = this.scaling.asArray();
  23956. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23957. serializationObject.isEnabled = this.isEnabled();
  23958. serializationObject.isVisible = this.isVisible;
  23959. serializationObject.infiniteDistance = this.infiniteDistance;
  23960. serializationObject.pickable = this.isPickable;
  23961. serializationObject.receiveShadows = this.receiveShadows;
  23962. serializationObject.billboardMode = this.billboardMode;
  23963. serializationObject.visibility = this.visibility;
  23964. serializationObject.checkCollisions = this.checkCollisions;
  23965. serializationObject.isBlocker = this.isBlocker;
  23966. // Parent
  23967. if (this.parent) {
  23968. serializationObject.parentId = this.parent.id;
  23969. }
  23970. // Geometry
  23971. var geometry = this._geometry;
  23972. if (geometry) {
  23973. var geometryId = geometry.id;
  23974. serializationObject.geometryId = geometryId;
  23975. // SubMeshes
  23976. serializationObject.subMeshes = [];
  23977. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23978. var subMesh = this.subMeshes[subIndex];
  23979. serializationObject.subMeshes.push({
  23980. materialIndex: subMesh.materialIndex,
  23981. verticesStart: subMesh.verticesStart,
  23982. verticesCount: subMesh.verticesCount,
  23983. indexStart: subMesh.indexStart,
  23984. indexCount: subMesh.indexCount
  23985. });
  23986. }
  23987. }
  23988. // Material
  23989. if (this.material) {
  23990. serializationObject.materialId = this.material.id;
  23991. }
  23992. else {
  23993. this.material = null;
  23994. }
  23995. // Skeleton
  23996. if (this.skeleton) {
  23997. serializationObject.skeletonId = this.skeleton.id;
  23998. }
  23999. // Physics
  24000. //TODO implement correct serialization for physics impostors.
  24001. if (this.getPhysicsImpostor()) {
  24002. var impostor = this.getPhysicsImpostor();
  24003. serializationObject.physicsMass = impostor.getParam("mass");
  24004. serializationObject.physicsFriction = impostor.getParam("friction");
  24005. serializationObject.physicsRestitution = impostor.getParam("mass");
  24006. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24007. }
  24008. // Metadata
  24009. if (this.metadata) {
  24010. serializationObject.metadata = this.metadata;
  24011. }
  24012. // Instances
  24013. serializationObject.instances = [];
  24014. for (var index = 0; index < this.instances.length; index++) {
  24015. var instance = this.instances[index];
  24016. var serializationInstance = {
  24017. name: instance.name,
  24018. position: instance.position.asArray(),
  24019. scaling: instance.scaling.asArray()
  24020. };
  24021. if (instance.rotationQuaternion) {
  24022. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24023. }
  24024. else if (instance.rotation) {
  24025. serializationInstance.rotation = instance.rotation.asArray();
  24026. }
  24027. serializationObject.instances.push(serializationInstance);
  24028. // Animations
  24029. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24030. serializationInstance.ranges = instance.serializeAnimationRanges();
  24031. }
  24032. // Animations
  24033. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24034. serializationObject.ranges = this.serializeAnimationRanges();
  24035. // Layer mask
  24036. serializationObject.layerMask = this.layerMask;
  24037. // Alpha
  24038. serializationObject.alphaIndex = this.alphaIndex;
  24039. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24040. // Overlay
  24041. serializationObject.overlayAlpha = this.overlayAlpha;
  24042. serializationObject.overlayColor = this.overlayColor.asArray();
  24043. serializationObject.renderOverlay = this.renderOverlay;
  24044. // Fog
  24045. serializationObject.applyFog = this.applyFog;
  24046. // Action Manager
  24047. if (this.actionManager) {
  24048. serializationObject.actions = this.actionManager.serialize(this.name);
  24049. }
  24050. };
  24051. // Statics
  24052. /**
  24053. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24054. * The parameter `parsedMesh` is the mesh to be copied.
  24055. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24056. */
  24057. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24058. var mesh;
  24059. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24060. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24061. }
  24062. else {
  24063. mesh = new Mesh(parsedMesh.name, scene);
  24064. }
  24065. mesh.id = parsedMesh.id;
  24066. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24067. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24068. if (parsedMesh.metadata !== undefined) {
  24069. mesh.metadata = parsedMesh.metadata;
  24070. }
  24071. if (parsedMesh.rotationQuaternion) {
  24072. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24073. }
  24074. else if (parsedMesh.rotation) {
  24075. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24076. }
  24077. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24078. if (parsedMesh.localMatrix) {
  24079. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24080. }
  24081. else if (parsedMesh.pivotMatrix) {
  24082. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24083. }
  24084. mesh.setEnabled(parsedMesh.isEnabled);
  24085. mesh.isVisible = parsedMesh.isVisible;
  24086. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24087. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24088. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24089. if (parsedMesh.applyFog !== undefined) {
  24090. mesh.applyFog = parsedMesh.applyFog;
  24091. }
  24092. if (parsedMesh.pickable !== undefined) {
  24093. mesh.isPickable = parsedMesh.pickable;
  24094. }
  24095. if (parsedMesh.alphaIndex !== undefined) {
  24096. mesh.alphaIndex = parsedMesh.alphaIndex;
  24097. }
  24098. mesh.receiveShadows = parsedMesh.receiveShadows;
  24099. mesh.billboardMode = parsedMesh.billboardMode;
  24100. if (parsedMesh.visibility !== undefined) {
  24101. mesh.visibility = parsedMesh.visibility;
  24102. }
  24103. mesh.checkCollisions = parsedMesh.checkCollisions;
  24104. if (parsedMesh.isBlocker !== undefined) {
  24105. mesh.isBlocker = parsedMesh.isBlocker;
  24106. }
  24107. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24108. // freezeWorldMatrix
  24109. if (parsedMesh.freezeWorldMatrix) {
  24110. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24111. }
  24112. // Parent
  24113. if (parsedMesh.parentId) {
  24114. mesh._waitingParentId = parsedMesh.parentId;
  24115. }
  24116. // Actions
  24117. if (parsedMesh.actions !== undefined) {
  24118. mesh._waitingActions = parsedMesh.actions;
  24119. }
  24120. // Overlay
  24121. if (parsedMesh.overlayAlpha !== undefined) {
  24122. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24123. }
  24124. if (parsedMesh.overlayColor !== undefined) {
  24125. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24126. }
  24127. if (parsedMesh.renderOverlay !== undefined) {
  24128. mesh.renderOverlay = parsedMesh.renderOverlay;
  24129. }
  24130. // Geometry
  24131. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24132. if (parsedMesh.delayLoadingFile) {
  24133. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24134. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24135. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24136. if (parsedMesh._binaryInfo) {
  24137. mesh._binaryInfo = parsedMesh._binaryInfo;
  24138. }
  24139. mesh._delayInfo = [];
  24140. if (parsedMesh.hasUVs) {
  24141. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24142. }
  24143. if (parsedMesh.hasUVs2) {
  24144. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24145. }
  24146. if (parsedMesh.hasUVs3) {
  24147. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24148. }
  24149. if (parsedMesh.hasUVs4) {
  24150. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24151. }
  24152. if (parsedMesh.hasUVs5) {
  24153. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24154. }
  24155. if (parsedMesh.hasUVs6) {
  24156. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24157. }
  24158. if (parsedMesh.hasColors) {
  24159. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24160. }
  24161. if (parsedMesh.hasMatricesIndices) {
  24162. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24163. }
  24164. if (parsedMesh.hasMatricesWeights) {
  24165. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24166. }
  24167. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24168. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24169. mesh._checkDelayState();
  24170. }
  24171. }
  24172. else {
  24173. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24174. }
  24175. // Material
  24176. if (parsedMesh.materialId) {
  24177. mesh.setMaterialByID(parsedMesh.materialId);
  24178. }
  24179. else {
  24180. mesh.material = null;
  24181. }
  24182. // Skeleton
  24183. if (parsedMesh.skeletonId > -1) {
  24184. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24185. if (parsedMesh.numBoneInfluencers) {
  24186. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24187. }
  24188. }
  24189. // Animations
  24190. if (parsedMesh.animations) {
  24191. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24192. var parsedAnimation = parsedMesh.animations[animationIndex];
  24193. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24194. }
  24195. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24196. }
  24197. if (parsedMesh.autoAnimate) {
  24198. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24199. }
  24200. // Layer Mask
  24201. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24202. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24203. }
  24204. else {
  24205. mesh.layerMask = 0x0FFFFFFF;
  24206. }
  24207. // Physics
  24208. if (parsedMesh.physicsImpostor) {
  24209. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24210. mass: parsedMesh.physicsMass,
  24211. friction: parsedMesh.physicsFriction,
  24212. restitution: parsedMesh.physicsRestitution
  24213. }, scene);
  24214. }
  24215. // Instances
  24216. if (parsedMesh.instances) {
  24217. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24218. var parsedInstance = parsedMesh.instances[index];
  24219. var instance = mesh.createInstance(parsedInstance.name);
  24220. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24221. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24222. if (parsedInstance.parentId) {
  24223. instance._waitingParentId = parsedInstance.parentId;
  24224. }
  24225. if (parsedInstance.rotationQuaternion) {
  24226. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24227. }
  24228. else if (parsedInstance.rotation) {
  24229. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24230. }
  24231. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24232. instance.checkCollisions = mesh.checkCollisions;
  24233. if (parsedMesh.animations) {
  24234. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24235. parsedAnimation = parsedMesh.animations[animationIndex];
  24236. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24237. }
  24238. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24239. }
  24240. }
  24241. }
  24242. return mesh;
  24243. };
  24244. /**
  24245. * Creates a ribbon mesh.
  24246. * Please consider using the same method from the MeshBuilder class instead.
  24247. * 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.
  24248. *
  24249. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24250. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24251. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24252. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24253. * 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.
  24254. * 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.
  24255. * 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
  24256. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24257. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24259. */
  24260. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24261. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24262. pathArray: pathArray,
  24263. closeArray: closeArray,
  24264. closePath: closePath,
  24265. offset: offset,
  24266. updatable: updatable,
  24267. sideOrientation: sideOrientation,
  24268. instance: instance
  24269. }, scene);
  24270. };
  24271. /**
  24272. * Creates a plane polygonal mesh. By default, this is a disc.
  24273. * Please consider using the same method from the MeshBuilder class instead.
  24274. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24275. * 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.
  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.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24281. var options = {
  24282. radius: radius,
  24283. tessellation: tessellation,
  24284. sideOrientation: sideOrientation,
  24285. updatable: updatable
  24286. };
  24287. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24288. };
  24289. /**
  24290. * Creates a box mesh.
  24291. * Please consider using the same method from the MeshBuilder class instead.
  24292. * The parameter `size` sets the size (float) of each box side (default 1).
  24293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24296. */
  24297. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24298. var options = {
  24299. size: size,
  24300. sideOrientation: sideOrientation,
  24301. updatable: updatable
  24302. };
  24303. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24304. };
  24305. /**
  24306. * Creates a sphere mesh.
  24307. * Please consider using the same method from the MeshBuilder class instead.
  24308. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24309. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24313. */
  24314. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24315. var options = {
  24316. segments: segments,
  24317. diameterX: diameter,
  24318. diameterY: diameter,
  24319. diameterZ: diameter,
  24320. sideOrientation: sideOrientation,
  24321. updatable: updatable
  24322. };
  24323. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24324. };
  24325. /**
  24326. * Creates a cylinder or a cone mesh.
  24327. * Please consider using the same method from the MeshBuilder class instead.
  24328. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24329. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24330. * 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.
  24331. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24332. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24334. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24336. */
  24337. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24338. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24339. if (scene !== undefined) {
  24340. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24341. updatable = scene;
  24342. }
  24343. scene = subdivisions;
  24344. subdivisions = 1;
  24345. }
  24346. var options = {
  24347. height: height,
  24348. diameterTop: diameterTop,
  24349. diameterBottom: diameterBottom,
  24350. tessellation: tessellation,
  24351. subdivisions: subdivisions,
  24352. sideOrientation: sideOrientation,
  24353. updatable: updatable
  24354. };
  24355. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24356. };
  24357. // Torus (Code from SharpDX.org)
  24358. /**
  24359. * Creates a torus mesh.
  24360. * Please consider using the same method from the MeshBuilder class instead.
  24361. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24362. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24363. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24367. */
  24368. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24369. var options = {
  24370. diameter: diameter,
  24371. thickness: thickness,
  24372. tessellation: tessellation,
  24373. sideOrientation: sideOrientation,
  24374. updatable: updatable
  24375. };
  24376. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24377. };
  24378. /**
  24379. * Creates a torus knot mesh.
  24380. * Please consider using the same method from the MeshBuilder class instead.
  24381. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24382. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24383. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24384. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24386. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24388. */
  24389. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24390. var options = {
  24391. radius: radius,
  24392. tube: tube,
  24393. radialSegments: radialSegments,
  24394. tubularSegments: tubularSegments,
  24395. p: p,
  24396. q: q,
  24397. sideOrientation: sideOrientation,
  24398. updatable: updatable
  24399. };
  24400. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24401. };
  24402. /**
  24403. * Creates a line mesh.
  24404. * Please consider using the same method from the MeshBuilder class instead.
  24405. * 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.
  24406. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24407. * The parameter `points` is an array successive Vector3.
  24408. * 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
  24409. * When updating an instance, remember that only point positions can change, not the number of points.
  24410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24411. */
  24412. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24413. var options = {
  24414. points: points,
  24415. updatable: updatable,
  24416. instance: instance
  24417. };
  24418. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24419. };
  24420. /**
  24421. * Creates a dashed line mesh.
  24422. * Please consider using the same method from the MeshBuilder class instead.
  24423. * 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.
  24424. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24425. * The parameter `points` is an array successive Vector3.
  24426. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24427. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24428. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24429. * 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
  24430. * When updating an instance, remember that only point positions can change, not the number of points.
  24431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24432. */
  24433. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24434. var options = {
  24435. points: points,
  24436. dashSize: dashSize,
  24437. gapSize: gapSize,
  24438. dashNb: dashNb,
  24439. updatable: updatable,
  24440. instance: instance
  24441. };
  24442. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24443. };
  24444. /**
  24445. * Creates an extruded shape mesh.
  24446. * 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.
  24447. * Please consider using the same method from the MeshBuilder class instead.
  24448. *
  24449. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24450. * 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
  24451. * extruded along the Z axis.
  24452. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24453. * 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.
  24454. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24455. * 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
  24456. * 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
  24457. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24459. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24460. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24461. */
  24462. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24463. var options = {
  24464. shape: shape,
  24465. path: path,
  24466. scale: scale,
  24467. rotation: rotation,
  24468. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24469. sideOrientation: sideOrientation,
  24470. instance: instance,
  24471. updatable: updatable
  24472. };
  24473. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24474. };
  24475. /**
  24476. * Creates an custom extruded shape mesh.
  24477. * 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.
  24478. * Please consider using the same method from the MeshBuilder class instead.
  24479. *
  24480. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24481. * 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
  24482. * extruded along the Z axis.
  24483. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24484. * 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
  24485. * and the distance of this point from the begining of the path :
  24486. * ```javascript
  24487. * var rotationFunction = function(i, distance) {
  24488. * // do things
  24489. * return rotationValue; }
  24490. * ```
  24491. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24492. * 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
  24493. * and the distance of this point from the begining of the path :
  24494. * ```javascript
  24495. * var scaleFunction = function(i, distance) {
  24496. * // do things
  24497. * return scaleValue;}
  24498. * ```
  24499. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24500. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24501. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24502. * 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
  24503. * 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
  24504. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24505. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24506. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24508. */
  24509. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24510. var options = {
  24511. shape: shape,
  24512. path: path,
  24513. scaleFunction: scaleFunction,
  24514. rotationFunction: rotationFunction,
  24515. ribbonCloseArray: ribbonCloseArray,
  24516. ribbonClosePath: ribbonClosePath,
  24517. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24518. sideOrientation: sideOrientation,
  24519. instance: instance,
  24520. updatable: updatable
  24521. };
  24522. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24523. };
  24524. /**
  24525. * Creates lathe mesh.
  24526. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24527. * Please consider using the same method from the MeshBuilder class instead.
  24528. * 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
  24529. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24530. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24531. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24532. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24534. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24535. */
  24536. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24537. var options = {
  24538. shape: shape,
  24539. radius: radius,
  24540. tessellation: tessellation,
  24541. sideOrientation: sideOrientation,
  24542. updatable: updatable
  24543. };
  24544. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24545. };
  24546. /**
  24547. * Creates a plane mesh.
  24548. * Please consider using the same method from the MeshBuilder class instead.
  24549. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24553. */
  24554. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24555. var options = {
  24556. size: size,
  24557. width: size,
  24558. height: size,
  24559. sideOrientation: sideOrientation,
  24560. updatable: updatable
  24561. };
  24562. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24563. };
  24564. /**
  24565. * Creates a ground mesh.
  24566. * Please consider using the same method from the MeshBuilder class instead.
  24567. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24568. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24570. */
  24571. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24572. var options = {
  24573. width: width,
  24574. height: height,
  24575. subdivisions: subdivisions,
  24576. updatable: updatable
  24577. };
  24578. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24579. };
  24580. /**
  24581. * Creates a tiled ground mesh.
  24582. * Please consider using the same method from the MeshBuilder class instead.
  24583. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24584. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24585. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24586. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24587. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24588. * numbers of subdivisions on the ground width and height of each tile.
  24589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24590. */
  24591. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24592. var options = {
  24593. xmin: xmin,
  24594. zmin: zmin,
  24595. xmax: xmax,
  24596. zmax: zmax,
  24597. subdivisions: subdivisions,
  24598. precision: precision,
  24599. updatable: updatable
  24600. };
  24601. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24602. };
  24603. /**
  24604. * Creates a ground mesh from a height map.
  24605. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24606. * Please consider using the same method from the MeshBuilder class instead.
  24607. * The parameter `url` sets the URL of the height map image resource.
  24608. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24609. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24610. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24611. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24612. * 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).
  24613. * This function is passed the newly built mesh :
  24614. * ```javascript
  24615. * function(mesh) { // do things
  24616. * return; }
  24617. * ```
  24618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24619. */
  24620. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24621. var options = {
  24622. width: width,
  24623. height: height,
  24624. subdivisions: subdivisions,
  24625. minHeight: minHeight,
  24626. maxHeight: maxHeight,
  24627. updatable: updatable,
  24628. onReady: onReady
  24629. };
  24630. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24631. };
  24632. /**
  24633. * Creates a tube mesh.
  24634. * 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.
  24635. * Please consider using the same method from the MeshBuilder class instead.
  24636. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24637. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24638. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24639. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24640. * 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.
  24641. * It must return a radius value (positive float) :
  24642. * ```javascript
  24643. * var radiusFunction = function(i, distance) {
  24644. * // do things
  24645. * return radius; }
  24646. * ```
  24647. * 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
  24648. * 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
  24649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24652. */
  24653. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24654. var options = {
  24655. path: path,
  24656. radius: radius,
  24657. tessellation: tessellation,
  24658. radiusFunction: radiusFunction,
  24659. arc: 1,
  24660. cap: cap,
  24661. updatable: updatable,
  24662. sideOrientation: sideOrientation,
  24663. instance: instance
  24664. };
  24665. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  24666. };
  24667. /**
  24668. * Creates a polyhedron mesh.
  24669. * Please consider using the same method from the MeshBuilder class instead.
  24670. * 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
  24671. * to choose the wanted type.
  24672. * The parameter `size` (positive float, default 1) sets the polygon size.
  24673. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  24674. * 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`.
  24675. * 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
  24676. * 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)`).
  24677. * 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
  24678. * 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.
  24679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24680. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24682. */
  24683. Mesh.CreatePolyhedron = function (name, options, scene) {
  24684. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  24685. };
  24686. /**
  24687. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  24688. * Please consider using the same method from the MeshBuilder class instead.
  24689. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  24690. * 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`).
  24691. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  24692. * 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.
  24693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24696. */
  24697. Mesh.CreateIcoSphere = function (name, options, scene) {
  24698. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  24699. };
  24700. /**
  24701. * Creates a decal mesh.
  24702. * Please consider using the same method from the MeshBuilder class instead.
  24703. * 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.
  24704. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  24705. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  24706. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  24707. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  24708. */
  24709. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  24710. var options = {
  24711. position: position,
  24712. normal: normal,
  24713. size: size,
  24714. angle: angle
  24715. };
  24716. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24717. };
  24718. // Skeletons
  24719. /**
  24720. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24721. */
  24722. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24723. var source;
  24724. if (!this._sourcePositions) {
  24725. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24726. this._sourcePositions = new Float32Array(source);
  24727. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24728. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24729. }
  24730. }
  24731. return this._sourcePositions;
  24732. };
  24733. /**
  24734. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24735. */
  24736. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24737. var source;
  24738. if (!this._sourceNormals) {
  24739. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24740. this._sourceNormals = new Float32Array(source);
  24741. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24742. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24743. }
  24744. }
  24745. return this._sourceNormals;
  24746. };
  24747. /**
  24748. * Updates the vertex buffer by applying transformation from the bones.
  24749. * Returns the Mesh.
  24750. *
  24751. * @param {skeleton} skeleton to apply
  24752. */
  24753. Mesh.prototype.applySkeleton = function (skeleton) {
  24754. if (!this.geometry) {
  24755. return this;
  24756. }
  24757. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24758. return this;
  24759. }
  24760. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24761. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24762. return this;
  24763. }
  24764. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24765. return this;
  24766. }
  24767. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24768. return this;
  24769. }
  24770. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24771. return this;
  24772. }
  24773. if (!this._sourcePositions) {
  24774. var submeshes = this.subMeshes.slice();
  24775. this.setPositionsForCPUSkinning();
  24776. this.subMeshes = submeshes;
  24777. }
  24778. if (!this._sourceNormals) {
  24779. this.setNormalsForCPUSkinning();
  24780. }
  24781. // positionsData checks for not being Float32Array will only pass at most once
  24782. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24783. if (!(positionsData instanceof Float32Array)) {
  24784. positionsData = new Float32Array(positionsData);
  24785. }
  24786. // normalsData checks for not being Float32Array will only pass at most once
  24787. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24788. if (!(normalsData instanceof Float32Array)) {
  24789. normalsData = new Float32Array(normalsData);
  24790. }
  24791. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24792. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24793. var needExtras = this.numBoneInfluencers > 4;
  24794. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24795. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24796. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24797. var tempVector3 = BABYLON.Vector3.Zero();
  24798. var finalMatrix = new BABYLON.Matrix();
  24799. var tempMatrix = new BABYLON.Matrix();
  24800. var matWeightIdx = 0;
  24801. var inf;
  24802. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24803. var weight;
  24804. for (inf = 0; inf < 4; inf++) {
  24805. weight = matricesWeightsData[matWeightIdx + inf];
  24806. if (weight > 0) {
  24807. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24808. finalMatrix.addToSelf(tempMatrix);
  24809. }
  24810. else
  24811. break;
  24812. }
  24813. if (needExtras) {
  24814. for (inf = 0; inf < 4; inf++) {
  24815. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24816. if (weight > 0) {
  24817. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24818. finalMatrix.addToSelf(tempMatrix);
  24819. }
  24820. else
  24821. break;
  24822. }
  24823. }
  24824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24825. tempVector3.toArray(positionsData, index);
  24826. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24827. tempVector3.toArray(normalsData, index);
  24828. finalMatrix.reset();
  24829. }
  24830. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24831. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24832. return this;
  24833. };
  24834. // Tools
  24835. /**
  24836. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24837. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24838. */
  24839. Mesh.MinMax = function (meshes) {
  24840. var minVector = null;
  24841. var maxVector = null;
  24842. meshes.forEach(function (mesh, index, array) {
  24843. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24844. if (!minVector) {
  24845. minVector = boundingBox.minimumWorld;
  24846. maxVector = boundingBox.maximumWorld;
  24847. }
  24848. else {
  24849. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24850. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24851. }
  24852. });
  24853. return {
  24854. min: minVector,
  24855. max: maxVector
  24856. };
  24857. };
  24858. /**
  24859. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24860. */
  24861. Mesh.Center = function (meshesOrMinMaxVector) {
  24862. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24863. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24864. };
  24865. /**
  24866. * Merge the array of meshes into a single mesh for performance reasons.
  24867. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24868. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24869. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24870. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24871. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24872. */
  24873. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24874. if (disposeSource === void 0) { disposeSource = true; }
  24875. var index;
  24876. if (!allow32BitsIndices) {
  24877. var totalVertices = 0;
  24878. // Counting vertices
  24879. for (index = 0; index < meshes.length; index++) {
  24880. if (meshes[index]) {
  24881. totalVertices += meshes[index].getTotalVertices();
  24882. if (totalVertices > 65536) {
  24883. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24884. return null;
  24885. }
  24886. }
  24887. }
  24888. }
  24889. // Merge
  24890. var vertexData;
  24891. var otherVertexData;
  24892. var indiceArray = new Array();
  24893. var source;
  24894. for (index = 0; index < meshes.length; index++) {
  24895. if (meshes[index]) {
  24896. meshes[index].computeWorldMatrix(true);
  24897. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24898. otherVertexData.transform(meshes[index].getWorldMatrix());
  24899. if (vertexData) {
  24900. vertexData.merge(otherVertexData);
  24901. }
  24902. else {
  24903. vertexData = otherVertexData;
  24904. source = meshes[index];
  24905. }
  24906. if (subdivideWithSubMeshes) {
  24907. indiceArray.push(meshes[index].getTotalIndices());
  24908. }
  24909. }
  24910. }
  24911. if (!meshSubclass) {
  24912. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24913. }
  24914. vertexData.applyToMesh(meshSubclass);
  24915. // Setting properties
  24916. meshSubclass.material = source.material;
  24917. meshSubclass.checkCollisions = source.checkCollisions;
  24918. // Cleaning
  24919. if (disposeSource) {
  24920. for (index = 0; index < meshes.length; index++) {
  24921. if (meshes[index]) {
  24922. meshes[index].dispose();
  24923. }
  24924. }
  24925. }
  24926. // Subdivide
  24927. if (subdivideWithSubMeshes) {
  24928. //-- Suppresions du submesh global
  24929. meshSubclass.releaseSubMeshes();
  24930. index = 0;
  24931. var offset = 0;
  24932. //-- aplique la subdivision en fonction du tableau d'indices
  24933. while (index < indiceArray.length) {
  24934. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24935. offset += indiceArray[index];
  24936. index++;
  24937. }
  24938. }
  24939. return meshSubclass;
  24940. };
  24941. return Mesh;
  24942. }(BABYLON.AbstractMesh));
  24943. // Consts
  24944. Mesh._FRONTSIDE = 0;
  24945. Mesh._BACKSIDE = 1;
  24946. Mesh._DOUBLESIDE = 2;
  24947. Mesh._DEFAULTSIDE = 0;
  24948. Mesh._NO_CAP = 0;
  24949. Mesh._CAP_START = 1;
  24950. Mesh._CAP_END = 2;
  24951. Mesh._CAP_ALL = 3;
  24952. BABYLON.Mesh = Mesh;
  24953. })(BABYLON || (BABYLON = {}));
  24954. //# sourceMappingURL=babylon.mesh.js.map
  24955. var BABYLON;
  24956. (function (BABYLON) {
  24957. var SubMesh = (function () {
  24958. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24959. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24960. this.materialIndex = materialIndex;
  24961. this.verticesStart = verticesStart;
  24962. this.verticesCount = verticesCount;
  24963. this.indexStart = indexStart;
  24964. this.indexCount = indexCount;
  24965. this._renderId = 0;
  24966. this._mesh = mesh;
  24967. this._renderingMesh = renderingMesh || mesh;
  24968. mesh.subMeshes.push(this);
  24969. this._trianglePlanes = [];
  24970. this._id = mesh.subMeshes.length - 1;
  24971. if (createBoundingBox) {
  24972. this.refreshBoundingInfo();
  24973. mesh.computeWorldMatrix(true);
  24974. }
  24975. }
  24976. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24977. get: function () {
  24978. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. /**
  24984. * Returns the submesh BoudingInfo object.
  24985. */
  24986. SubMesh.prototype.getBoundingInfo = function () {
  24987. if (this.IsGlobal) {
  24988. return this._mesh.getBoundingInfo();
  24989. }
  24990. return this._boundingInfo;
  24991. };
  24992. /**
  24993. * Sets the submesh BoundingInfo.
  24994. * Return the SubMesh.
  24995. */
  24996. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24997. this._boundingInfo = boundingInfo;
  24998. return this;
  24999. };
  25000. /**
  25001. * Returns the mesh of the current submesh.
  25002. */
  25003. SubMesh.prototype.getMesh = function () {
  25004. return this._mesh;
  25005. };
  25006. /**
  25007. * Returns the rendering mesh of the submesh.
  25008. */
  25009. SubMesh.prototype.getRenderingMesh = function () {
  25010. return this._renderingMesh;
  25011. };
  25012. /**
  25013. * Returns the submesh material.
  25014. */
  25015. SubMesh.prototype.getMaterial = function () {
  25016. var rootMaterial = this._renderingMesh.material;
  25017. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25018. var multiMaterial = rootMaterial;
  25019. return multiMaterial.getSubMaterial(this.materialIndex);
  25020. }
  25021. if (!rootMaterial) {
  25022. return this._mesh.getScene().defaultMaterial;
  25023. }
  25024. return rootMaterial;
  25025. };
  25026. // Methods
  25027. /**
  25028. * Sets a new updated BoundingInfo object to the submesh.
  25029. * Returns the SubMesh.
  25030. */
  25031. SubMesh.prototype.refreshBoundingInfo = function () {
  25032. this._lastColliderWorldVertices = null;
  25033. if (this.IsGlobal) {
  25034. return;
  25035. }
  25036. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25037. if (!data) {
  25038. this._boundingInfo = this._mesh._boundingInfo;
  25039. return;
  25040. }
  25041. var indices = this._renderingMesh.getIndices();
  25042. var extend;
  25043. //is this the only submesh?
  25044. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25045. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25046. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  25047. }
  25048. else {
  25049. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25050. }
  25051. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25052. return this;
  25053. };
  25054. SubMesh.prototype._checkCollision = function (collider) {
  25055. return this.getBoundingInfo()._checkCollision(collider);
  25056. };
  25057. /**
  25058. * Updates the submesh BoundingInfo.
  25059. * Returns the Submesh.
  25060. */
  25061. SubMesh.prototype.updateBoundingInfo = function (world) {
  25062. if (!this.getBoundingInfo()) {
  25063. this.refreshBoundingInfo();
  25064. }
  25065. this.getBoundingInfo().update(world);
  25066. return this;
  25067. };
  25068. /**
  25069. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25070. * Boolean returned.
  25071. */
  25072. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25073. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  25074. };
  25075. /**
  25076. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25077. * Boolean returned.
  25078. */
  25079. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25080. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  25081. };
  25082. /**
  25083. * Renders the submesh.
  25084. * Returns it.
  25085. */
  25086. SubMesh.prototype.render = function (enableAlphaMode) {
  25087. this._renderingMesh.render(this, enableAlphaMode);
  25088. return this;
  25089. };
  25090. /**
  25091. * Returns a new Index Buffer.
  25092. * Type returned : WebGLBuffer.
  25093. */
  25094. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25095. if (!this._linesIndexBuffer) {
  25096. var linesIndices = [];
  25097. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25098. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25099. }
  25100. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25101. this.linesIndexCount = linesIndices.length;
  25102. }
  25103. return this._linesIndexBuffer;
  25104. };
  25105. /**
  25106. * True is the passed Ray intersects the submesh bounding box.
  25107. * Boolean returned.
  25108. */
  25109. SubMesh.prototype.canIntersects = function (ray) {
  25110. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  25111. };
  25112. /**
  25113. * Returns an object IntersectionInfo.
  25114. */
  25115. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25116. var intersectInfo = null;
  25117. // LineMesh first as it's also a Mesh...
  25118. if (this._mesh instanceof BABYLON.LinesMesh) {
  25119. var lineMesh = this._mesh;
  25120. // Line test
  25121. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25122. var p0 = positions[indices[index]];
  25123. var p1 = positions[indices[index + 1]];
  25124. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25125. if (length < 0) {
  25126. continue;
  25127. }
  25128. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25129. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25130. if (fastCheck) {
  25131. break;
  25132. }
  25133. }
  25134. }
  25135. }
  25136. else {
  25137. // Triangles test
  25138. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25139. var p0 = positions[indices[index]];
  25140. var p1 = positions[indices[index + 1]];
  25141. var p2 = positions[indices[index + 2]];
  25142. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25143. if (currentIntersectInfo) {
  25144. if (currentIntersectInfo.distance < 0) {
  25145. continue;
  25146. }
  25147. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25148. intersectInfo = currentIntersectInfo;
  25149. intersectInfo.faceId = index / 3;
  25150. if (fastCheck) {
  25151. break;
  25152. }
  25153. }
  25154. }
  25155. }
  25156. }
  25157. return intersectInfo;
  25158. };
  25159. // Clone
  25160. /**
  25161. * Creates a new Submesh from the passed Mesh.
  25162. */
  25163. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25164. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25165. if (!this.IsGlobal) {
  25166. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  25167. }
  25168. return result;
  25169. };
  25170. // Dispose
  25171. /**
  25172. * Disposes the Submesh.
  25173. * Returns nothing.
  25174. */
  25175. SubMesh.prototype.dispose = function () {
  25176. if (this._linesIndexBuffer) {
  25177. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25178. this._linesIndexBuffer = null;
  25179. }
  25180. // Remove from mesh
  25181. var index = this._mesh.subMeshes.indexOf(this);
  25182. this._mesh.subMeshes.splice(index, 1);
  25183. };
  25184. // Statics
  25185. /**
  25186. * Creates a new Submesh from the passed parameters :
  25187. * - materialIndex (integer) : the index of the main mesh material.
  25188. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25189. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25190. * - mesh (Mesh) : the main mesh to create the submesh from.
  25191. * - renderingMesh (optional Mesh) : rendering mesh.
  25192. */
  25193. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25194. var minVertexIndex = Number.MAX_VALUE;
  25195. var maxVertexIndex = -Number.MAX_VALUE;
  25196. renderingMesh = renderingMesh || mesh;
  25197. var indices = renderingMesh.getIndices();
  25198. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25199. var vertexIndex = indices[index];
  25200. if (vertexIndex < minVertexIndex)
  25201. minVertexIndex = vertexIndex;
  25202. if (vertexIndex > maxVertexIndex)
  25203. maxVertexIndex = vertexIndex;
  25204. }
  25205. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25206. };
  25207. return SubMesh;
  25208. }());
  25209. BABYLON.SubMesh = SubMesh;
  25210. })(BABYLON || (BABYLON = {}));
  25211. //# sourceMappingURL=babylon.subMesh.js.map
  25212. var BABYLON;
  25213. (function (BABYLON) {
  25214. var MeshBuilder = (function () {
  25215. function MeshBuilder() {
  25216. }
  25217. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25218. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25219. return BABYLON.Mesh.DOUBLESIDE;
  25220. }
  25221. if (orientation === undefined || orientation === null) {
  25222. return BABYLON.Mesh.FRONTSIDE;
  25223. }
  25224. return orientation;
  25225. };
  25226. /**
  25227. * Creates a box mesh.
  25228. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25229. * The parameter `size` sets the size (float) of each box side (default 1).
  25230. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25231. * 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).
  25232. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25236. */
  25237. MeshBuilder.CreateBox = function (name, options, scene) {
  25238. var box = new BABYLON.Mesh(name, scene);
  25239. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25240. box.sideOrientation = options.sideOrientation;
  25241. var vertexData = BABYLON.VertexData.CreateBox(options);
  25242. vertexData.applyToMesh(box, options.updatable);
  25243. return box;
  25244. };
  25245. /**
  25246. * Creates a sphere mesh.
  25247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25248. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25249. * 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`).
  25250. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25251. * 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
  25252. * 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).
  25253. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25256. */
  25257. MeshBuilder.CreateSphere = function (name, options, scene) {
  25258. var sphere = new BABYLON.Mesh(name, scene);
  25259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25260. sphere.sideOrientation = options.sideOrientation;
  25261. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25262. vertexData.applyToMesh(sphere, options.updatable);
  25263. return sphere;
  25264. };
  25265. /**
  25266. * Creates a plane polygonal mesh. By default, this is a disc.
  25267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25268. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25269. * 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.
  25270. * 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
  25271. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25272. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreateDisc = function (name, options, scene) {
  25276. var disc = new BABYLON.Mesh(name, scene);
  25277. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25278. disc.sideOrientation = options.sideOrientation;
  25279. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25280. vertexData.applyToMesh(disc, options.updatable);
  25281. return disc;
  25282. };
  25283. /**
  25284. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25286. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25287. * 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`).
  25288. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25289. * 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.
  25290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25291. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25293. */
  25294. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25295. var sphere = new BABYLON.Mesh(name, scene);
  25296. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25297. sphere.sideOrientation = options.sideOrientation;
  25298. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25299. vertexData.applyToMesh(sphere, options.updatable);
  25300. return sphere;
  25301. };
  25302. ;
  25303. /**
  25304. * Creates a ribbon mesh.
  25305. * 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.
  25306. *
  25307. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25308. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25309. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25310. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25311. * 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.
  25312. * 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.
  25313. * 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
  25314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25316. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25318. */
  25319. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25320. var pathArray = options.pathArray;
  25321. var closeArray = options.closeArray;
  25322. var closePath = options.closePath;
  25323. var offset = options.offset;
  25324. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25325. var instance = options.instance;
  25326. var updatable = options.updatable;
  25327. if (instance) {
  25328. // positionFunction : ribbon case
  25329. // only pathArray and sideOrientation parameters are taken into account for positions update
  25330. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25331. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25332. var positionFunction = function (positions) {
  25333. var minlg = pathArray[0].length;
  25334. var i = 0;
  25335. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25336. for (var si = 1; si <= ns; si++) {
  25337. for (var p = 0; p < pathArray.length; p++) {
  25338. var path = pathArray[p];
  25339. var l = path.length;
  25340. minlg = (minlg < l) ? minlg : l;
  25341. var j = 0;
  25342. while (j < minlg) {
  25343. positions[i] = path[j].x;
  25344. positions[i + 1] = path[j].y;
  25345. positions[i + 2] = path[j].z;
  25346. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25347. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25348. }
  25349. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25350. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25351. }
  25352. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25353. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25354. }
  25355. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25356. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25357. }
  25358. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25359. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25360. }
  25361. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25362. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25363. }
  25364. j++;
  25365. i += 3;
  25366. }
  25367. if (instance._closePath) {
  25368. positions[i] = path[0].x;
  25369. positions[i + 1] = path[0].y;
  25370. positions[i + 2] = path[0].z;
  25371. i += 3;
  25372. }
  25373. }
  25374. }
  25375. };
  25376. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25377. positionFunction(positions);
  25378. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25379. instance._boundingInfo.update(instance._worldMatrix);
  25380. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25381. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25382. var indices = instance.getIndices();
  25383. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25384. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25385. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25386. if (instance._closePath) {
  25387. var indexFirst = 0;
  25388. var indexLast = 0;
  25389. for (var p = 0; p < pathArray.length; p++) {
  25390. indexFirst = instance._idx[p] * 3;
  25391. if (p + 1 < pathArray.length) {
  25392. indexLast = (instance._idx[p + 1] - 1) * 3;
  25393. }
  25394. else {
  25395. indexLast = normals.length - 3;
  25396. }
  25397. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25398. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25399. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25400. normals[indexLast] = normals[indexFirst];
  25401. normals[indexLast + 1] = normals[indexFirst + 1];
  25402. normals[indexLast + 2] = normals[indexFirst + 2];
  25403. }
  25404. }
  25405. if (!(instance.areNormalsFrozen)) {
  25406. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25407. }
  25408. }
  25409. return instance;
  25410. }
  25411. else {
  25412. var ribbon = new BABYLON.Mesh(name, scene);
  25413. ribbon.sideOrientation = sideOrientation;
  25414. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25415. if (closePath) {
  25416. ribbon._idx = vertexData._idx;
  25417. }
  25418. ribbon._closePath = closePath;
  25419. ribbon._closeArray = closeArray;
  25420. vertexData.applyToMesh(ribbon, updatable);
  25421. return ribbon;
  25422. }
  25423. };
  25424. /**
  25425. * Creates a cylinder or a cone mesh.
  25426. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25427. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25428. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25429. * 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.
  25430. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25431. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25432. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25433. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25434. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25435. * 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).
  25436. * 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
  25437. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25438. * 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
  25439. * 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.
  25440. * If `enclose` is false, a ring surface is one element.
  25441. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25442. * 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
  25443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25446. */
  25447. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25448. var cylinder = new BABYLON.Mesh(name, scene);
  25449. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25450. cylinder.sideOrientation = options.sideOrientation;
  25451. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25452. vertexData.applyToMesh(cylinder, options.updatable);
  25453. return cylinder;
  25454. };
  25455. /**
  25456. * Creates a torus mesh.
  25457. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25458. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25459. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25460. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25461. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25462. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25463. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25464. */
  25465. MeshBuilder.CreateTorus = function (name, options, scene) {
  25466. var torus = new BABYLON.Mesh(name, scene);
  25467. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25468. torus.sideOrientation = options.sideOrientation;
  25469. var vertexData = BABYLON.VertexData.CreateTorus(options);
  25470. vertexData.applyToMesh(torus, options.updatable);
  25471. return torus;
  25472. };
  25473. /**
  25474. * Creates a torus knot mesh.
  25475. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  25476. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25477. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25478. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25479. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25480. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25481. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25482. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25483. */
  25484. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  25485. var torusKnot = new BABYLON.Mesh(name, scene);
  25486. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25487. torusKnot.sideOrientation = options.sideOrientation;
  25488. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  25489. vertexData.applyToMesh(torusKnot, options.updatable);
  25490. return torusKnot;
  25491. };
  25492. /**
  25493. * Creates a line system mesh.
  25494. * A line system is a pool of many lines gathered in a single mesh.
  25495. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  25496. * 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.
  25497. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  25498. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  25499. * 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
  25500. * 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
  25501. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  25502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25503. */
  25504. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  25505. var instance = options.instance;
  25506. var lines = options.lines;
  25507. if (instance) {
  25508. var positionFunction = function (positions) {
  25509. var i = 0;
  25510. for (var l = 0; l < lines.length; l++) {
  25511. var points = lines[l];
  25512. for (var p = 0; p < points.length; p++) {
  25513. positions[i] = points[p].x;
  25514. positions[i + 1] = points[p].y;
  25515. positions[i + 2] = points[p].z;
  25516. i += 3;
  25517. }
  25518. }
  25519. };
  25520. instance.updateMeshPositions(positionFunction, false);
  25521. return instance;
  25522. }
  25523. // line system creation
  25524. var lineSystem = new BABYLON.LinesMesh(name, scene);
  25525. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  25526. vertexData.applyToMesh(lineSystem, options.updatable);
  25527. return lineSystem;
  25528. };
  25529. /**
  25530. * Creates a line mesh.
  25531. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  25532. * 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.
  25533. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25534. * The parameter `points` is an array successive Vector3.
  25535. * 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
  25536. * When updating an instance, remember that only point positions can change, not the number of points.
  25537. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25538. */
  25539. MeshBuilder.CreateLines = function (name, options, scene) {
  25540. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  25541. return lines;
  25542. };
  25543. /**
  25544. * Creates a dashed line mesh.
  25545. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  25546. * 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.
  25547. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25548. * The parameter `points` is an array successive Vector3.
  25549. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25550. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25551. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25552. * 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
  25553. * When updating an instance, remember that only point positions can change, not the number of points.
  25554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25555. */
  25556. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  25557. var points = options.points;
  25558. var instance = options.instance;
  25559. var gapSize = options.gapSize;
  25560. var dashNb = options.dashNb;
  25561. var dashSize = options.dashSize;
  25562. if (instance) {
  25563. var positionFunction = function (positions) {
  25564. var curvect = BABYLON.Vector3.Zero();
  25565. var nbSeg = positions.length / 6;
  25566. var lg = 0;
  25567. var nb = 0;
  25568. var shft = 0;
  25569. var dashshft = 0;
  25570. var curshft = 0;
  25571. var p = 0;
  25572. var i = 0;
  25573. var j = 0;
  25574. for (i = 0; i < points.length - 1; i++) {
  25575. points[i + 1].subtractToRef(points[i], curvect);
  25576. lg += curvect.length();
  25577. }
  25578. shft = lg / nbSeg;
  25579. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  25580. for (i = 0; i < points.length - 1; i++) {
  25581. points[i + 1].subtractToRef(points[i], curvect);
  25582. nb = Math.floor(curvect.length() / shft);
  25583. curvect.normalize();
  25584. j = 0;
  25585. while (j < nb && p < positions.length) {
  25586. curshft = shft * j;
  25587. positions[p] = points[i].x + curshft * curvect.x;
  25588. positions[p + 1] = points[i].y + curshft * curvect.y;
  25589. positions[p + 2] = points[i].z + curshft * curvect.z;
  25590. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  25591. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  25592. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  25593. p += 6;
  25594. j++;
  25595. }
  25596. }
  25597. while (p < positions.length) {
  25598. positions[p] = points[i].x;
  25599. positions[p + 1] = points[i].y;
  25600. positions[p + 2] = points[i].z;
  25601. p += 3;
  25602. }
  25603. };
  25604. instance.updateMeshPositions(positionFunction, false);
  25605. return instance;
  25606. }
  25607. // dashed lines creation
  25608. var dashedLines = new BABYLON.LinesMesh(name, scene);
  25609. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  25610. vertexData.applyToMesh(dashedLines, options.updatable);
  25611. dashedLines.dashSize = dashSize;
  25612. dashedLines.gapSize = gapSize;
  25613. return dashedLines;
  25614. };
  25615. /**
  25616. * Creates an extruded shape mesh.
  25617. * 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.
  25618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  25619. *
  25620. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25621. * 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
  25622. * extruded along the Z axis.
  25623. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25624. * 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.
  25625. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25626. * 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
  25627. * 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
  25628. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25629. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25630. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25631. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25633. */
  25634. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  25635. var path = options.path;
  25636. var shape = options.shape;
  25637. var scale = options.scale || 1;
  25638. var rotation = options.rotation || 0;
  25639. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25640. var updatable = options.updatable;
  25641. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25642. var instance = options.instance;
  25643. var invertUV = options.invertUV || false;
  25644. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  25645. };
  25646. /**
  25647. * Creates an custom extruded shape mesh.
  25648. * 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.
  25649. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  25650. *
  25651. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25652. * 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
  25653. * extruded along the Z axis.
  25654. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25655. * 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
  25656. * and the distance of this point from the begining of the path :
  25657. * ```javascript
  25658. * var rotationFunction = function(i, distance) {
  25659. * // do things
  25660. * return rotationValue; }
  25661. * ```
  25662. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25663. * 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
  25664. * and the distance of this point from the begining of the path :
  25665. * ```javascript
  25666. * var scaleFunction = function(i, distance) {
  25667. * // do things
  25668. * return scaleValue;}
  25669. * ```
  25670. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25671. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25672. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25673. * 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
  25674. * 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
  25675. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25678. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25680. */
  25681. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  25682. var path = options.path;
  25683. var shape = options.shape;
  25684. var scaleFunction = options.scaleFunction || (function () { return 1; });
  25685. var rotationFunction = options.rotationFunction || (function () { return 0; });
  25686. var ribbonCloseArray = options.ribbonCloseArray || false;
  25687. var ribbonClosePath = options.ribbonClosePath || false;
  25688. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  25689. var updatable = options.updatable;
  25690. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25691. var instance = options.instance;
  25692. var invertUV = options.invertUV || false;
  25693. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  25694. };
  25695. /**
  25696. * Creates lathe mesh.
  25697. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25698. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  25699. *
  25700. * 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
  25701. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25702. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25703. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25704. * 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.
  25705. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  25706. * 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
  25707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25708. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25709. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25711. */
  25712. MeshBuilder.CreateLathe = function (name, options, scene) {
  25713. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  25714. var closed = (options.closed === undefined) ? true : options.closed;
  25715. var shape = options.shape;
  25716. var radius = options.radius || 1;
  25717. var tessellation = options.tessellation || 64;
  25718. var updatable = options.updatable;
  25719. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25720. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25721. var pi2 = Math.PI * 2;
  25722. var paths = new Array();
  25723. var invertUV = options.invertUV || false;
  25724. var i = 0;
  25725. var p = 0;
  25726. var step = pi2 / tessellation * arc;
  25727. var rotated;
  25728. var path = new Array();
  25729. ;
  25730. for (i = 0; i <= tessellation; i++) {
  25731. var path = [];
  25732. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  25733. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  25734. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  25735. }
  25736. for (p = 0; p < shape.length; p++) {
  25737. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  25738. path.push(rotated);
  25739. }
  25740. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  25741. 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));
  25742. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  25743. }
  25744. paths.push(path);
  25745. }
  25746. // lathe ribbon
  25747. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  25748. return lathe;
  25749. };
  25750. /**
  25751. * Creates a plane mesh.
  25752. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25753. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25754. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  25755. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  25756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25759. */
  25760. MeshBuilder.CreatePlane = function (name, options, scene) {
  25761. var plane = new BABYLON.Mesh(name, scene);
  25762. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25763. plane.sideOrientation = options.sideOrientation;
  25764. var vertexData = BABYLON.VertexData.CreatePlane(options);
  25765. vertexData.applyToMesh(plane, options.updatable);
  25766. if (options.sourcePlane) {
  25767. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  25768. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  25769. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  25770. plane.rotate(vectorProduct, product);
  25771. }
  25772. return plane;
  25773. };
  25774. /**
  25775. * Creates a ground mesh.
  25776. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  25777. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25778. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25780. */
  25781. MeshBuilder.CreateGround = function (name, options, scene) {
  25782. var ground = new BABYLON.GroundMesh(name, scene);
  25783. ground._setReady(false);
  25784. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25785. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25786. ground._width = options.width || 1;
  25787. ground._height = options.height || 1;
  25788. ground._maxX = ground._width / 2;
  25789. ground._maxZ = ground._height / 2;
  25790. ground._minX = -ground._maxX;
  25791. ground._minZ = -ground._maxZ;
  25792. var vertexData = BABYLON.VertexData.CreateGround(options);
  25793. vertexData.applyToMesh(ground, options.updatable);
  25794. ground._setReady(true);
  25795. return ground;
  25796. };
  25797. /**
  25798. * Creates a tiled ground mesh.
  25799. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  25800. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25801. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25802. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25803. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25804. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25805. * numbers of subdivisions on the ground width and height of each tile.
  25806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25807. */
  25808. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  25809. var tiledGround = new BABYLON.Mesh(name, scene);
  25810. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  25811. vertexData.applyToMesh(tiledGround, options.updatable);
  25812. return tiledGround;
  25813. };
  25814. /**
  25815. * Creates a ground mesh from a height map.
  25816. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25817. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  25818. * The parameter `url` sets the URL of the height map image resource.
  25819. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25820. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25821. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25822. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25823. * 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.
  25824. * 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).
  25825. * This function is passed the newly built mesh :
  25826. * ```javascript
  25827. * function(mesh) { // do things
  25828. * return; }
  25829. * ```
  25830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25831. */
  25832. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  25833. var width = options.width || 10.0;
  25834. var height = options.height || 10.0;
  25835. var subdivisions = options.subdivisions || 1 | 0;
  25836. var minHeight = options.minHeight || 0.0;
  25837. var maxHeight = options.maxHeight || 10.0;
  25838. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25839. var updatable = options.updatable;
  25840. var onReady = options.onReady;
  25841. var ground = new BABYLON.GroundMesh(name, scene);
  25842. ground._subdivisionsX = subdivisions;
  25843. ground._subdivisionsY = subdivisions;
  25844. ground._width = width;
  25845. ground._height = height;
  25846. ground._maxX = ground._width / 2.0;
  25847. ground._maxZ = ground._height / 2.0;
  25848. ground._minX = -ground._maxX;
  25849. ground._minZ = -ground._maxZ;
  25850. ground._setReady(false);
  25851. var onload = function (img) {
  25852. // Getting height map data
  25853. var canvas = document.createElement("canvas");
  25854. var context = canvas.getContext("2d");
  25855. var bufferWidth = img.width;
  25856. var bufferHeight = img.height;
  25857. canvas.width = bufferWidth;
  25858. canvas.height = bufferHeight;
  25859. context.drawImage(img, 0, 0);
  25860. // Create VertexData from map data
  25861. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25862. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  25863. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  25864. width: width, height: height,
  25865. subdivisions: subdivisions,
  25866. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  25867. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  25868. });
  25869. vertexData.applyToMesh(ground, updatable);
  25870. ground._setReady(true);
  25871. //execute ready callback, if set
  25872. if (onReady) {
  25873. onReady(ground);
  25874. }
  25875. };
  25876. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25877. return ground;
  25878. };
  25879. /**
  25880. * Creates a tube mesh.
  25881. * 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.
  25882. *
  25883. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  25884. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25885. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25886. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25887. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25888. * 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.
  25889. * It must return a radius value (positive float) :
  25890. * ```javascript
  25891. * var radiusFunction = function(i, distance) {
  25892. * // do things
  25893. * return radius; }
  25894. * ```
  25895. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  25896. * 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
  25897. * 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
  25898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25899. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25900. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25902. */
  25903. MeshBuilder.CreateTube = function (name, options, scene) {
  25904. var path = options.path;
  25905. var radius = options.radius || 1.0;
  25906. var tessellation = options.tessellation || 64 | 0;
  25907. var radiusFunction = options.radiusFunction;
  25908. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  25909. var invertUV = options.invertUV || false;
  25910. var updatable = options.updatable;
  25911. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25912. var instance = options.instance;
  25913. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  25914. // tube geometry
  25915. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  25916. var tangents = path3D.getTangents();
  25917. var normals = path3D.getNormals();
  25918. var distances = path3D.getDistances();
  25919. var pi2 = Math.PI * 2;
  25920. var step = pi2 / tessellation * arc;
  25921. var returnRadius = function () { return radius; };
  25922. var radiusFunctionFinal = radiusFunction || returnRadius;
  25923. var circlePath;
  25924. var rad;
  25925. var normal;
  25926. var rotated;
  25927. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  25928. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  25929. for (var i = 0; i < path.length; i++) {
  25930. rad = radiusFunctionFinal(i, distances[i]); // current radius
  25931. circlePath = Array(); // current circle array
  25932. normal = normals[i]; // current normal
  25933. for (var t = 0; t < tessellation; t++) {
  25934. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  25935. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  25936. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  25937. rotated.scaleInPlace(rad).addInPlace(path[i]);
  25938. circlePath[t] = rotated;
  25939. }
  25940. circlePaths[index] = circlePath;
  25941. index++;
  25942. }
  25943. // cap
  25944. var capPath = function (nbPoints, pathIndex) {
  25945. var pointCap = Array();
  25946. for (var i = 0; i < nbPoints; i++) {
  25947. pointCap.push(path[pathIndex]);
  25948. }
  25949. return pointCap;
  25950. };
  25951. switch (cap) {
  25952. case BABYLON.Mesh.NO_CAP:
  25953. break;
  25954. case BABYLON.Mesh.CAP_START:
  25955. circlePaths[0] = capPath(tessellation, 0);
  25956. circlePaths[1] = circlePaths[2].slice(0);
  25957. break;
  25958. case BABYLON.Mesh.CAP_END:
  25959. circlePaths[index] = circlePaths[index - 1].slice(0);
  25960. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25961. break;
  25962. case BABYLON.Mesh.CAP_ALL:
  25963. circlePaths[0] = capPath(tessellation, 0);
  25964. circlePaths[1] = circlePaths[2].slice(0);
  25965. circlePaths[index] = circlePaths[index - 1].slice(0);
  25966. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  25967. break;
  25968. default:
  25969. break;
  25970. }
  25971. return circlePaths;
  25972. };
  25973. var path3D;
  25974. var pathArray;
  25975. if (instance) {
  25976. var arc = options.arc || instance.arc;
  25977. path3D = (instance.path3D).update(path);
  25978. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  25979. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  25980. instance.path3D = path3D;
  25981. instance.pathArray = pathArray;
  25982. instance.arc = arc;
  25983. return instance;
  25984. }
  25985. // tube creation
  25986. path3D = new BABYLON.Path3D(path);
  25987. var newPathArray = new Array();
  25988. cap = (cap < 0 || cap > 3) ? 0 : cap;
  25989. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  25990. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  25991. tube.pathArray = pathArray;
  25992. tube.path3D = path3D;
  25993. tube.tessellation = tessellation;
  25994. tube.cap = cap;
  25995. tube.arc = options.arc;
  25996. return tube;
  25997. };
  25998. /**
  25999. * Creates a polyhedron mesh.
  26000. *
  26001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26002. * 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
  26003. * to choose the wanted type.
  26004. * The parameter `size` (positive float, default 1) sets the polygon size.
  26005. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26006. * 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`.
  26007. * 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
  26008. * 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)`).
  26009. * 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
  26010. * 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.
  26011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26014. */
  26015. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26016. var polyhedron = new BABYLON.Mesh(name, scene);
  26017. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26018. polyhedron.sideOrientation = options.sideOrientation;
  26019. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26020. vertexData.applyToMesh(polyhedron, options.updatable);
  26021. return polyhedron;
  26022. };
  26023. /**
  26024. * Creates a decal mesh.
  26025. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  26026. * 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.
  26027. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26028. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26029. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26030. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26031. */
  26032. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  26033. var indices = sourceMesh.getIndices();
  26034. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26035. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26036. var position = options.position || BABYLON.Vector3.Zero();
  26037. var normal = options.normal || BABYLON.Vector3.Up();
  26038. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  26039. var angle = options.angle || 0;
  26040. // Getting correct rotation
  26041. if (!normal) {
  26042. var target = new BABYLON.Vector3(0, 0, 1);
  26043. var camera = sourceMesh.getScene().activeCamera;
  26044. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  26045. normal = camera.globalPosition.subtract(cameraWorldTarget);
  26046. }
  26047. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  26048. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  26049. var pitch = Math.atan2(normal.y, len);
  26050. // Matrix
  26051. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  26052. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  26053. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  26054. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  26055. var vertexData = new BABYLON.VertexData();
  26056. vertexData.indices = [];
  26057. vertexData.positions = [];
  26058. vertexData.normals = [];
  26059. vertexData.uvs = [];
  26060. var currentVertexDataIndex = 0;
  26061. var extractDecalVector3 = function (indexId) {
  26062. var vertexId = indices[indexId];
  26063. var result = new BABYLON.PositionNormalVertex();
  26064. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  26065. // Send vector to decal local world
  26066. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  26067. // Get normal
  26068. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  26069. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  26070. return result;
  26071. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  26072. var clip = function (vertices, axis) {
  26073. if (vertices.length === 0) {
  26074. return vertices;
  26075. }
  26076. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  26077. var clipVertices = function (v0, v1) {
  26078. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  26079. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  26080. };
  26081. var result = new Array();
  26082. for (var index = 0; index < vertices.length; index += 3) {
  26083. var v1Out;
  26084. var v2Out;
  26085. var v3Out;
  26086. var total = 0;
  26087. var nV1, nV2, nV3, nV4;
  26088. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  26089. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  26090. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  26091. v1Out = d1 > 0;
  26092. v2Out = d2 > 0;
  26093. v3Out = d3 > 0;
  26094. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  26095. switch (total) {
  26096. case 0:
  26097. result.push(vertices[index]);
  26098. result.push(vertices[index + 1]);
  26099. result.push(vertices[index + 2]);
  26100. break;
  26101. case 1:
  26102. if (v1Out) {
  26103. nV1 = vertices[index + 1];
  26104. nV2 = vertices[index + 2];
  26105. nV3 = clipVertices(vertices[index], nV1);
  26106. nV4 = clipVertices(vertices[index], nV2);
  26107. }
  26108. if (v2Out) {
  26109. nV1 = vertices[index];
  26110. nV2 = vertices[index + 2];
  26111. nV3 = clipVertices(vertices[index + 1], nV1);
  26112. nV4 = clipVertices(vertices[index + 1], nV2);
  26113. result.push(nV3);
  26114. result.push(nV2.clone());
  26115. result.push(nV1.clone());
  26116. result.push(nV2.clone());
  26117. result.push(nV3.clone());
  26118. result.push(nV4);
  26119. break;
  26120. }
  26121. if (v3Out) {
  26122. nV1 = vertices[index];
  26123. nV2 = vertices[index + 1];
  26124. nV3 = clipVertices(vertices[index + 2], nV1);
  26125. nV4 = clipVertices(vertices[index + 2], nV2);
  26126. }
  26127. result.push(nV1.clone());
  26128. result.push(nV2.clone());
  26129. result.push(nV3);
  26130. result.push(nV4);
  26131. result.push(nV3.clone());
  26132. result.push(nV2.clone());
  26133. break;
  26134. case 2:
  26135. if (!v1Out) {
  26136. nV1 = vertices[index].clone();
  26137. nV2 = clipVertices(nV1, vertices[index + 1]);
  26138. nV3 = clipVertices(nV1, vertices[index + 2]);
  26139. result.push(nV1);
  26140. result.push(nV2);
  26141. result.push(nV3);
  26142. }
  26143. if (!v2Out) {
  26144. nV1 = vertices[index + 1].clone();
  26145. nV2 = clipVertices(nV1, vertices[index + 2]);
  26146. nV3 = clipVertices(nV1, vertices[index]);
  26147. result.push(nV1);
  26148. result.push(nV2);
  26149. result.push(nV3);
  26150. }
  26151. if (!v3Out) {
  26152. nV1 = vertices[index + 2].clone();
  26153. nV2 = clipVertices(nV1, vertices[index]);
  26154. nV3 = clipVertices(nV1, vertices[index + 1]);
  26155. result.push(nV1);
  26156. result.push(nV2);
  26157. result.push(nV3);
  26158. }
  26159. break;
  26160. case 3:
  26161. break;
  26162. }
  26163. }
  26164. return result;
  26165. };
  26166. for (var index = 0; index < indices.length; index += 3) {
  26167. var faceVertices = new Array();
  26168. faceVertices.push(extractDecalVector3(index));
  26169. faceVertices.push(extractDecalVector3(index + 1));
  26170. faceVertices.push(extractDecalVector3(index + 2));
  26171. // Clip
  26172. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26173. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26174. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26175. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26176. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26177. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26178. if (faceVertices.length === 0) {
  26179. continue;
  26180. }
  26181. // Add UVs and get back to world
  26182. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26183. var vertex = faceVertices[vIndex];
  26184. //TODO check for Int32Array | Uint32Array | Uint16Array
  26185. vertexData.indices.push(currentVertexDataIndex);
  26186. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26187. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26188. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26189. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26190. currentVertexDataIndex++;
  26191. }
  26192. }
  26193. // Return mesh
  26194. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26195. vertexData.applyToMesh(decal);
  26196. decal.position = position.clone();
  26197. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26198. return decal;
  26199. };
  26200. // Privates
  26201. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26202. // extrusion geometry
  26203. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26204. var tangents = path3D.getTangents();
  26205. var normals = path3D.getNormals();
  26206. var binormals = path3D.getBinormals();
  26207. var distances = path3D.getDistances();
  26208. var angle = 0;
  26209. var returnScale = function () { return scale; };
  26210. var returnRotation = function () { return rotation; };
  26211. var rotate = custom ? rotateFunction : returnRotation;
  26212. var scl = custom ? scaleFunction : returnScale;
  26213. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26214. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26215. for (var i = 0; i < curve.length; i++) {
  26216. var shapePath = new Array();
  26217. var angleStep = rotate(i, distances[i]);
  26218. var scaleRatio = scl(i, distances[i]);
  26219. for (var p = 0; p < shape.length; p++) {
  26220. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26221. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26222. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26223. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26224. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26225. shapePath[p] = rotated;
  26226. }
  26227. shapePaths[index] = shapePath;
  26228. angle += angleStep;
  26229. index++;
  26230. }
  26231. // cap
  26232. var capPath = function (shapePath) {
  26233. var pointCap = Array();
  26234. var barycenter = BABYLON.Vector3.Zero();
  26235. var i;
  26236. for (i = 0; i < shapePath.length; i++) {
  26237. barycenter.addInPlace(shapePath[i]);
  26238. }
  26239. barycenter.scaleInPlace(1.0 / shapePath.length);
  26240. for (i = 0; i < shapePath.length; i++) {
  26241. pointCap.push(barycenter);
  26242. }
  26243. return pointCap;
  26244. };
  26245. switch (cap) {
  26246. case BABYLON.Mesh.NO_CAP:
  26247. break;
  26248. case BABYLON.Mesh.CAP_START:
  26249. shapePaths[0] = capPath(shapePaths[2]);
  26250. shapePaths[1] = shapePaths[2];
  26251. break;
  26252. case BABYLON.Mesh.CAP_END:
  26253. shapePaths[index] = shapePaths[index - 1];
  26254. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26255. break;
  26256. case BABYLON.Mesh.CAP_ALL:
  26257. shapePaths[0] = capPath(shapePaths[2]);
  26258. shapePaths[1] = shapePaths[2];
  26259. shapePaths[index] = shapePaths[index - 1];
  26260. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26261. break;
  26262. default:
  26263. break;
  26264. }
  26265. return shapePaths;
  26266. };
  26267. var path3D;
  26268. var pathArray;
  26269. if (instance) {
  26270. path3D = (instance.path3D).update(curve);
  26271. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26272. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26273. return instance;
  26274. }
  26275. // extruded shape creation
  26276. path3D = new BABYLON.Path3D(curve);
  26277. var newShapePaths = new Array();
  26278. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26279. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26280. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26281. extrudedGeneric.pathArray = pathArray;
  26282. extrudedGeneric.path3D = path3D;
  26283. extrudedGeneric.cap = cap;
  26284. return extrudedGeneric;
  26285. };
  26286. return MeshBuilder;
  26287. }());
  26288. BABYLON.MeshBuilder = MeshBuilder;
  26289. })(BABYLON || (BABYLON = {}));
  26290. //# sourceMappingURL=babylon.meshBuilder.js.map
  26291. var BABYLON;
  26292. (function (BABYLON) {
  26293. var BaseTexture = (function () {
  26294. function BaseTexture(scene) {
  26295. this.hasAlpha = false;
  26296. this.getAlphaFromRGB = false;
  26297. this.level = 1;
  26298. this.coordinatesIndex = 0;
  26299. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26300. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26301. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26302. this.anisotropicFilteringLevel = 4;
  26303. this.isCube = false;
  26304. this.isRenderTarget = false;
  26305. this.animations = new Array();
  26306. /**
  26307. * An event triggered when the texture is disposed.
  26308. * @type {BABYLON.Observable}
  26309. */
  26310. this.onDisposeObservable = new BABYLON.Observable();
  26311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26312. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26313. this._scene.textures.push(this);
  26314. this._uid = null;
  26315. }
  26316. Object.defineProperty(BaseTexture.prototype, "uid", {
  26317. get: function () {
  26318. if (!this._uid) {
  26319. this._uid = BABYLON.Tools.RandomId();
  26320. }
  26321. return this._uid;
  26322. },
  26323. enumerable: true,
  26324. configurable: true
  26325. });
  26326. BaseTexture.prototype.toString = function () {
  26327. return this.name;
  26328. };
  26329. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26330. set: function (callback) {
  26331. if (this._onDisposeObserver) {
  26332. this.onDisposeObservable.remove(this._onDisposeObserver);
  26333. }
  26334. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26335. },
  26336. enumerable: true,
  26337. configurable: true
  26338. });
  26339. BaseTexture.prototype.getScene = function () {
  26340. return this._scene;
  26341. };
  26342. BaseTexture.prototype.getTextureMatrix = function () {
  26343. return null;
  26344. };
  26345. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26346. return null;
  26347. };
  26348. BaseTexture.prototype.getInternalTexture = function () {
  26349. return this._texture;
  26350. };
  26351. BaseTexture.prototype.isReady = function () {
  26352. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26353. return true;
  26354. }
  26355. if (this._texture) {
  26356. return this._texture.isReady;
  26357. }
  26358. return false;
  26359. };
  26360. BaseTexture.prototype.getSize = function () {
  26361. if (this._texture._width) {
  26362. return new BABYLON.Size(this._texture._width, this._texture._height);
  26363. }
  26364. if (this._texture._size) {
  26365. return new BABYLON.Size(this._texture._size, this._texture._size);
  26366. }
  26367. return BABYLON.Size.Zero();
  26368. };
  26369. BaseTexture.prototype.getBaseSize = function () {
  26370. if (!this.isReady() || !this._texture)
  26371. return BABYLON.Size.Zero();
  26372. if (this._texture._size) {
  26373. return new BABYLON.Size(this._texture._size, this._texture._size);
  26374. }
  26375. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26376. };
  26377. BaseTexture.prototype.scale = function (ratio) {
  26378. };
  26379. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26380. get: function () {
  26381. return false;
  26382. },
  26383. enumerable: true,
  26384. configurable: true
  26385. });
  26386. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26387. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26388. for (var index = 0; index < texturesCache.length; index++) {
  26389. var texturesCacheEntry = texturesCache[index];
  26390. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26391. texturesCache.splice(index, 1);
  26392. return;
  26393. }
  26394. }
  26395. };
  26396. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26397. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26398. for (var index = 0; index < texturesCache.length; index++) {
  26399. var texturesCacheEntry = texturesCache[index];
  26400. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26401. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26402. texturesCacheEntry.references++;
  26403. return texturesCacheEntry;
  26404. }
  26405. }
  26406. }
  26407. return null;
  26408. };
  26409. BaseTexture.prototype.delayLoad = function () {
  26410. };
  26411. BaseTexture.prototype.clone = function () {
  26412. return null;
  26413. };
  26414. BaseTexture.prototype.releaseInternalTexture = function () {
  26415. if (this._texture) {
  26416. this._scene.getEngine().releaseInternalTexture(this._texture);
  26417. delete this._texture;
  26418. }
  26419. };
  26420. BaseTexture.prototype.dispose = function () {
  26421. // Animations
  26422. this.getScene().stopAnimation(this);
  26423. // Remove from scene
  26424. this._scene._removePendingData(this);
  26425. var index = this._scene.textures.indexOf(this);
  26426. if (index >= 0) {
  26427. this._scene.textures.splice(index, 1);
  26428. }
  26429. if (this._texture === undefined) {
  26430. return;
  26431. }
  26432. // Release
  26433. this.releaseInternalTexture();
  26434. // Callback
  26435. this.onDisposeObservable.notifyObservers(this);
  26436. this.onDisposeObservable.clear();
  26437. };
  26438. BaseTexture.prototype.serialize = function () {
  26439. if (!this.name) {
  26440. return null;
  26441. }
  26442. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26443. // Animations
  26444. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26445. return serializationObject;
  26446. };
  26447. return BaseTexture;
  26448. }());
  26449. __decorate([
  26450. BABYLON.serialize()
  26451. ], BaseTexture.prototype, "name", void 0);
  26452. __decorate([
  26453. BABYLON.serialize()
  26454. ], BaseTexture.prototype, "hasAlpha", void 0);
  26455. __decorate([
  26456. BABYLON.serialize()
  26457. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26458. __decorate([
  26459. BABYLON.serialize()
  26460. ], BaseTexture.prototype, "level", void 0);
  26461. __decorate([
  26462. BABYLON.serialize()
  26463. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26464. __decorate([
  26465. BABYLON.serialize()
  26466. ], BaseTexture.prototype, "coordinatesMode", void 0);
  26467. __decorate([
  26468. BABYLON.serialize()
  26469. ], BaseTexture.prototype, "wrapU", void 0);
  26470. __decorate([
  26471. BABYLON.serialize()
  26472. ], BaseTexture.prototype, "wrapV", void 0);
  26473. __decorate([
  26474. BABYLON.serialize()
  26475. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26476. __decorate([
  26477. BABYLON.serialize()
  26478. ], BaseTexture.prototype, "isCube", void 0);
  26479. __decorate([
  26480. BABYLON.serialize()
  26481. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26482. BABYLON.BaseTexture = BaseTexture;
  26483. })(BABYLON || (BABYLON = {}));
  26484. //# sourceMappingURL=babylon.baseTexture.js.map
  26485. var BABYLON;
  26486. (function (BABYLON) {
  26487. var Texture = (function (_super) {
  26488. __extends(Texture, _super);
  26489. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26490. if (noMipmap === void 0) { noMipmap = false; }
  26491. if (invertY === void 0) { invertY = true; }
  26492. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26493. if (onLoad === void 0) { onLoad = null; }
  26494. if (onError === void 0) { onError = null; }
  26495. if (buffer === void 0) { buffer = null; }
  26496. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26497. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26498. var _this = _super.call(this, scene) || this;
  26499. _this.uOffset = 0;
  26500. _this.vOffset = 0;
  26501. _this.uScale = 1.0;
  26502. _this.vScale = 1.0;
  26503. _this.uAng = 0;
  26504. _this.vAng = 0;
  26505. _this.wAng = 0;
  26506. _this.name = url;
  26507. _this.url = url;
  26508. _this._noMipmap = noMipmap;
  26509. _this._invertY = invertY;
  26510. _this._samplingMode = samplingMode;
  26511. _this._buffer = buffer;
  26512. _this._deleteBuffer = deleteBuffer;
  26513. _this._format = format;
  26514. if (!url) {
  26515. return _this;
  26516. }
  26517. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  26518. var load = function () {
  26519. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  26520. _this.onLoadObservable.notifyObservers(true);
  26521. }
  26522. if (onLoad) {
  26523. onLoad();
  26524. }
  26525. };
  26526. if (!_this._texture) {
  26527. if (!scene.useDelayedTextureLoading) {
  26528. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  26529. if (deleteBuffer) {
  26530. delete _this._buffer;
  26531. }
  26532. }
  26533. else {
  26534. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26535. _this._delayedOnLoad = load;
  26536. _this._delayedOnError = onError;
  26537. }
  26538. }
  26539. else {
  26540. if (_this._texture.isReady) {
  26541. BABYLON.Tools.SetImmediate(function () { return load(); });
  26542. }
  26543. else {
  26544. _this._texture.onLoadedCallbacks.push(load);
  26545. }
  26546. }
  26547. return _this;
  26548. }
  26549. Object.defineProperty(Texture.prototype, "noMipmap", {
  26550. get: function () {
  26551. return this._noMipmap;
  26552. },
  26553. enumerable: true,
  26554. configurable: true
  26555. });
  26556. Texture.prototype.delayLoad = function () {
  26557. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26558. return;
  26559. }
  26560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26561. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26562. if (!this._texture) {
  26563. 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);
  26564. if (this._deleteBuffer) {
  26565. delete this._buffer;
  26566. }
  26567. }
  26568. };
  26569. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26570. if (!this._texture) {
  26571. return;
  26572. }
  26573. this._samplingMode = samplingMode;
  26574. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26575. };
  26576. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26577. x *= this.uScale;
  26578. y *= this.vScale;
  26579. x -= 0.5 * this.uScale;
  26580. y -= 0.5 * this.vScale;
  26581. z -= 0.5;
  26582. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26583. t.x += 0.5 * this.uScale + this.uOffset;
  26584. t.y += 0.5 * this.vScale + this.vOffset;
  26585. t.z += 0.5;
  26586. };
  26587. Texture.prototype.getTextureMatrix = function () {
  26588. if (this.uOffset === this._cachedUOffset &&
  26589. this.vOffset === this._cachedVOffset &&
  26590. this.uScale === this._cachedUScale &&
  26591. this.vScale === this._cachedVScale &&
  26592. this.uAng === this._cachedUAng &&
  26593. this.vAng === this._cachedVAng &&
  26594. this.wAng === this._cachedWAng) {
  26595. return this._cachedTextureMatrix;
  26596. }
  26597. this._cachedUOffset = this.uOffset;
  26598. this._cachedVOffset = this.vOffset;
  26599. this._cachedUScale = this.uScale;
  26600. this._cachedVScale = this.vScale;
  26601. this._cachedUAng = this.uAng;
  26602. this._cachedVAng = this.vAng;
  26603. this._cachedWAng = this.wAng;
  26604. if (!this._cachedTextureMatrix) {
  26605. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26606. this._rowGenerationMatrix = new BABYLON.Matrix();
  26607. this._t0 = BABYLON.Vector3.Zero();
  26608. this._t1 = BABYLON.Vector3.Zero();
  26609. this._t2 = BABYLON.Vector3.Zero();
  26610. }
  26611. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26612. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26613. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26614. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26615. this._t1.subtractInPlace(this._t0);
  26616. this._t2.subtractInPlace(this._t0);
  26617. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26618. this._cachedTextureMatrix.m[0] = this._t1.x;
  26619. this._cachedTextureMatrix.m[1] = this._t1.y;
  26620. this._cachedTextureMatrix.m[2] = this._t1.z;
  26621. this._cachedTextureMatrix.m[4] = this._t2.x;
  26622. this._cachedTextureMatrix.m[5] = this._t2.y;
  26623. this._cachedTextureMatrix.m[6] = this._t2.z;
  26624. this._cachedTextureMatrix.m[8] = this._t0.x;
  26625. this._cachedTextureMatrix.m[9] = this._t0.y;
  26626. this._cachedTextureMatrix.m[10] = this._t0.z;
  26627. return this._cachedTextureMatrix;
  26628. };
  26629. Texture.prototype.getReflectionTextureMatrix = function () {
  26630. if (this.uOffset === this._cachedUOffset &&
  26631. this.vOffset === this._cachedVOffset &&
  26632. this.uScale === this._cachedUScale &&
  26633. this.vScale === this._cachedVScale &&
  26634. this.coordinatesMode === this._cachedCoordinatesMode) {
  26635. return this._cachedTextureMatrix;
  26636. }
  26637. if (!this._cachedTextureMatrix) {
  26638. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26639. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26640. }
  26641. this._cachedCoordinatesMode = this.coordinatesMode;
  26642. switch (this.coordinatesMode) {
  26643. case Texture.PLANAR_MODE:
  26644. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26645. this._cachedTextureMatrix[0] = this.uScale;
  26646. this._cachedTextureMatrix[5] = this.vScale;
  26647. this._cachedTextureMatrix[12] = this.uOffset;
  26648. this._cachedTextureMatrix[13] = this.vOffset;
  26649. break;
  26650. case Texture.PROJECTION_MODE:
  26651. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26652. this._projectionModeMatrix.m[0] = 0.5;
  26653. this._projectionModeMatrix.m[5] = -0.5;
  26654. this._projectionModeMatrix.m[10] = 0.0;
  26655. this._projectionModeMatrix.m[12] = 0.5;
  26656. this._projectionModeMatrix.m[13] = 0.5;
  26657. this._projectionModeMatrix.m[14] = 1.0;
  26658. this._projectionModeMatrix.m[15] = 1.0;
  26659. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26660. break;
  26661. default:
  26662. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26663. break;
  26664. }
  26665. return this._cachedTextureMatrix;
  26666. };
  26667. Texture.prototype.clone = function () {
  26668. var _this = this;
  26669. return BABYLON.SerializationHelper.Clone(function () {
  26670. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26671. }, this);
  26672. };
  26673. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26674. get: function () {
  26675. if (!this._onLoadObservarble) {
  26676. this._onLoadObservarble = new BABYLON.Observable();
  26677. }
  26678. return this._onLoadObservarble;
  26679. },
  26680. enumerable: true,
  26681. configurable: true
  26682. });
  26683. // Statics
  26684. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26685. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26686. if (onLoad === void 0) { onLoad = null; }
  26687. if (onError === void 0) { onError = null; }
  26688. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26689. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26690. };
  26691. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26692. if (parsedTexture.customType) {
  26693. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26694. return customTexture.Parse(parsedTexture, scene, rootUrl);
  26695. }
  26696. if (parsedTexture.isCube) {
  26697. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26698. }
  26699. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26700. return null;
  26701. }
  26702. var texture = BABYLON.SerializationHelper.Parse(function () {
  26703. if (parsedTexture.mirrorPlane) {
  26704. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26705. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26706. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26707. return mirrorTexture;
  26708. }
  26709. else if (parsedTexture.isRenderTarget) {
  26710. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  26711. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26712. return renderTargetTexture;
  26713. }
  26714. else {
  26715. var texture;
  26716. if (parsedTexture.base64String) {
  26717. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  26718. }
  26719. else {
  26720. texture = new Texture(rootUrl + parsedTexture.name, scene);
  26721. }
  26722. return texture;
  26723. }
  26724. }, parsedTexture, scene);
  26725. // Animations
  26726. if (parsedTexture.animations) {
  26727. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26728. var parsedAnimation = parsedTexture.animations[animationIndex];
  26729. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26730. }
  26731. }
  26732. return texture;
  26733. };
  26734. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26735. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26736. if (noMipmap === void 0) { noMipmap = false; }
  26737. if (invertY === void 0) { invertY = true; }
  26738. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26739. if (onLoad === void 0) { onLoad = null; }
  26740. if (onError === void 0) { onError = null; }
  26741. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26742. if (name.substr(0, 5) !== "data:") {
  26743. name = "data:" + name;
  26744. }
  26745. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26746. };
  26747. return Texture;
  26748. }(BABYLON.BaseTexture));
  26749. // Constants
  26750. Texture.NEAREST_SAMPLINGMODE = 1;
  26751. Texture.BILINEAR_SAMPLINGMODE = 2;
  26752. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26753. Texture.EXPLICIT_MODE = 0;
  26754. Texture.SPHERICAL_MODE = 1;
  26755. Texture.PLANAR_MODE = 2;
  26756. Texture.CUBIC_MODE = 3;
  26757. Texture.PROJECTION_MODE = 4;
  26758. Texture.SKYBOX_MODE = 5;
  26759. Texture.INVCUBIC_MODE = 6;
  26760. Texture.EQUIRECTANGULAR_MODE = 7;
  26761. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26762. Texture.CLAMP_ADDRESSMODE = 0;
  26763. Texture.WRAP_ADDRESSMODE = 1;
  26764. Texture.MIRROR_ADDRESSMODE = 2;
  26765. __decorate([
  26766. BABYLON.serialize()
  26767. ], Texture.prototype, "url", void 0);
  26768. __decorate([
  26769. BABYLON.serialize()
  26770. ], Texture.prototype, "uOffset", void 0);
  26771. __decorate([
  26772. BABYLON.serialize()
  26773. ], Texture.prototype, "vOffset", void 0);
  26774. __decorate([
  26775. BABYLON.serialize()
  26776. ], Texture.prototype, "uScale", void 0);
  26777. __decorate([
  26778. BABYLON.serialize()
  26779. ], Texture.prototype, "vScale", void 0);
  26780. __decorate([
  26781. BABYLON.serialize()
  26782. ], Texture.prototype, "uAng", void 0);
  26783. __decorate([
  26784. BABYLON.serialize()
  26785. ], Texture.prototype, "vAng", void 0);
  26786. __decorate([
  26787. BABYLON.serialize()
  26788. ], Texture.prototype, "wAng", void 0);
  26789. BABYLON.Texture = Texture;
  26790. })(BABYLON || (BABYLON = {}));
  26791. //# sourceMappingURL=babylon.texture.js.map
  26792. var BABYLON;
  26793. (function (BABYLON) {
  26794. var CubeTexture = (function (_super) {
  26795. __extends(CubeTexture, _super);
  26796. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  26797. if (onLoad === void 0) { onLoad = null; }
  26798. if (onError === void 0) { onError = null; }
  26799. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26800. var _this = _super.call(this, scene) || this;
  26801. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  26802. _this.name = rootUrl;
  26803. _this.url = rootUrl;
  26804. _this._noMipmap = noMipmap;
  26805. _this.hasAlpha = false;
  26806. _this._format = format;
  26807. if (!rootUrl && !files) {
  26808. return _this;
  26809. }
  26810. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  26811. if (!files) {
  26812. if (!extensions) {
  26813. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  26814. }
  26815. files = [];
  26816. for (var index = 0; index < extensions.length; index++) {
  26817. files.push(rootUrl + extensions[index]);
  26818. }
  26819. _this._extensions = extensions;
  26820. }
  26821. _this._files = files;
  26822. if (!_this._texture) {
  26823. if (!scene.useDelayedTextureLoading) {
  26824. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  26825. }
  26826. else {
  26827. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26828. }
  26829. }
  26830. else if (onLoad) {
  26831. if (_this._texture.isReady) {
  26832. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  26833. }
  26834. else {
  26835. _this._texture.onLoadedCallbacks.push(onLoad);
  26836. }
  26837. }
  26838. _this.isCube = true;
  26839. _this._textureMatrix = BABYLON.Matrix.Identity();
  26840. return _this;
  26841. }
  26842. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  26843. return new CubeTexture("", scene, null, noMipmap, files);
  26844. };
  26845. // Methods
  26846. CubeTexture.prototype.delayLoad = function () {
  26847. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26848. return;
  26849. }
  26850. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26851. this._texture = this._getFromCache(this.url, this._noMipmap);
  26852. if (!this._texture) {
  26853. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  26854. }
  26855. };
  26856. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  26857. return this._textureMatrix;
  26858. };
  26859. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  26860. var texture = BABYLON.SerializationHelper.Parse(function () {
  26861. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  26862. }, parsedTexture, scene);
  26863. // Animations
  26864. if (parsedTexture.animations) {
  26865. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26866. var parsedAnimation = parsedTexture.animations[animationIndex];
  26867. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26868. }
  26869. }
  26870. return texture;
  26871. };
  26872. CubeTexture.prototype.clone = function () {
  26873. var _this = this;
  26874. return BABYLON.SerializationHelper.Clone(function () {
  26875. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  26876. }, this);
  26877. };
  26878. return CubeTexture;
  26879. }(BABYLON.BaseTexture));
  26880. BABYLON.CubeTexture = CubeTexture;
  26881. })(BABYLON || (BABYLON = {}));
  26882. //# sourceMappingURL=babylon.cubeTexture.js.map
  26883. var BABYLON;
  26884. (function (BABYLON) {
  26885. var RenderTargetTexture = (function (_super) {
  26886. __extends(RenderTargetTexture, _super);
  26887. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  26888. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  26889. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26890. if (isCube === void 0) { isCube = false; }
  26891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26892. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  26893. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  26894. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  26895. _this.isCube = isCube;
  26896. /**
  26897. * Use this list to define the list of mesh you want to render.
  26898. */
  26899. _this.renderList = new Array();
  26900. _this.renderParticles = true;
  26901. _this.renderSprites = false;
  26902. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  26903. // Events
  26904. /**
  26905. * An event triggered when the texture is unbind.
  26906. * @type {BABYLON.Observable}
  26907. */
  26908. _this.onAfterUnbindObservable = new BABYLON.Observable();
  26909. /**
  26910. * An event triggered before rendering the texture
  26911. * @type {BABYLON.Observable}
  26912. */
  26913. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26914. /**
  26915. * An event triggered after rendering the texture
  26916. * @type {BABYLON.Observable}
  26917. */
  26918. _this.onAfterRenderObservable = new BABYLON.Observable();
  26919. /**
  26920. * An event triggered after the texture clear
  26921. * @type {BABYLON.Observable}
  26922. */
  26923. _this.onClearObservable = new BABYLON.Observable();
  26924. _this._currentRefreshId = -1;
  26925. _this._refreshRate = 1;
  26926. _this._samples = 1;
  26927. _this.name = name;
  26928. _this.isRenderTarget = true;
  26929. _this._size = size;
  26930. _this._generateMipMaps = generateMipMaps;
  26931. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  26932. _this._renderTargetOptions = {
  26933. generateMipMaps: generateMipMaps,
  26934. type: type,
  26935. samplingMode: samplingMode,
  26936. generateDepthBuffer: generateDepthBuffer,
  26937. generateStencilBuffer: generateStencilBuffer
  26938. };
  26939. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26940. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26941. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26942. }
  26943. if (isCube) {
  26944. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  26945. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  26946. _this._textureMatrix = BABYLON.Matrix.Identity();
  26947. }
  26948. else {
  26949. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  26950. }
  26951. // Rendering groups
  26952. _this._renderingManager = new BABYLON.RenderingManager(scene);
  26953. return _this;
  26954. }
  26955. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  26956. get: function () {
  26957. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  26958. },
  26959. enumerable: true,
  26960. configurable: true
  26961. });
  26962. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  26963. get: function () {
  26964. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  26965. },
  26966. enumerable: true,
  26967. configurable: true
  26968. });
  26969. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  26970. get: function () {
  26971. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  26972. },
  26973. enumerable: true,
  26974. configurable: true
  26975. });
  26976. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  26977. set: function (callback) {
  26978. if (this._onAfterUnbindObserver) {
  26979. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  26980. }
  26981. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  26987. set: function (callback) {
  26988. if (this._onBeforeRenderObserver) {
  26989. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26990. }
  26991. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26992. },
  26993. enumerable: true,
  26994. configurable: true
  26995. });
  26996. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  26997. set: function (callback) {
  26998. if (this._onAfterRenderObserver) {
  26999. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27000. }
  27001. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27002. },
  27003. enumerable: true,
  27004. configurable: true
  27005. });
  27006. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  27007. set: function (callback) {
  27008. if (this._onClearObserver) {
  27009. this.onClearObservable.remove(this._onClearObserver);
  27010. }
  27011. this._onClearObserver = this.onClearObservable.add(callback);
  27012. },
  27013. enumerable: true,
  27014. configurable: true
  27015. });
  27016. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  27017. get: function () {
  27018. return this._samples;
  27019. },
  27020. set: function (value) {
  27021. if (this._samples === value) {
  27022. return;
  27023. }
  27024. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  27025. },
  27026. enumerable: true,
  27027. configurable: true
  27028. });
  27029. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  27030. this._currentRefreshId = -1;
  27031. };
  27032. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  27033. get: function () {
  27034. return this._refreshRate;
  27035. },
  27036. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27037. set: function (value) {
  27038. this._refreshRate = value;
  27039. this.resetRefreshCounter();
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. RenderTargetTexture.prototype._shouldRender = function () {
  27045. if (this._currentRefreshId === -1) {
  27046. this._currentRefreshId = 1;
  27047. return true;
  27048. }
  27049. if (this.refreshRate === this._currentRefreshId) {
  27050. this._currentRefreshId = 1;
  27051. return true;
  27052. }
  27053. this._currentRefreshId++;
  27054. return false;
  27055. };
  27056. RenderTargetTexture.prototype.isReady = function () {
  27057. if (!this.getScene().renderTargetsEnabled) {
  27058. return false;
  27059. }
  27060. return _super.prototype.isReady.call(this);
  27061. };
  27062. RenderTargetTexture.prototype.getRenderSize = function () {
  27063. return this._size;
  27064. };
  27065. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  27066. get: function () {
  27067. return true;
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. RenderTargetTexture.prototype.scale = function (ratio) {
  27073. var newSize = this._size * ratio;
  27074. this.resize(newSize);
  27075. };
  27076. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  27077. if (this.isCube) {
  27078. return this._textureMatrix;
  27079. }
  27080. return _super.prototype.getReflectionTextureMatrix.call(this);
  27081. };
  27082. RenderTargetTexture.prototype.resize = function (size) {
  27083. this.releaseInternalTexture();
  27084. if (this.isCube) {
  27085. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  27086. }
  27087. else {
  27088. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  27089. }
  27090. };
  27091. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  27092. var scene = this.getScene();
  27093. var engine = scene.getEngine();
  27094. if (this.useCameraPostProcesses !== undefined) {
  27095. useCameraPostProcess = this.useCameraPostProcesses;
  27096. }
  27097. if (this._waitingRenderList) {
  27098. this.renderList = [];
  27099. for (var index = 0; index < this._waitingRenderList.length; index++) {
  27100. var id = this._waitingRenderList[index];
  27101. this.renderList.push(scene.getMeshByID(id));
  27102. }
  27103. delete this._waitingRenderList;
  27104. }
  27105. // Is predicate defined?
  27106. if (this.renderListPredicate) {
  27107. this.renderList.splice(0); // Clear previous renderList
  27108. var sceneMeshes = this.getScene().meshes;
  27109. for (var index = 0; index < sceneMeshes.length; index++) {
  27110. var mesh = sceneMeshes[index];
  27111. if (this.renderListPredicate(mesh)) {
  27112. this.renderList.push(mesh);
  27113. }
  27114. }
  27115. }
  27116. if (this.renderList && this.renderList.length === 0) {
  27117. return;
  27118. }
  27119. // Set custom projection.
  27120. // Needs to be before binding to prevent changing the aspect ratio.
  27121. if (this.activeCamera) {
  27122. engine.setViewport(this.activeCamera.viewport);
  27123. if (this.activeCamera !== scene.activeCamera) {
  27124. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  27125. }
  27126. }
  27127. else {
  27128. engine.setViewport(scene.activeCamera.viewport);
  27129. }
  27130. // Prepare renderingManager
  27131. this._renderingManager.reset();
  27132. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  27133. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  27134. var sceneRenderId = scene.getRenderId();
  27135. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  27136. var mesh = currentRenderList[meshIndex];
  27137. if (mesh) {
  27138. if (!mesh.isReady()) {
  27139. // Reset _currentRefreshId
  27140. this.resetRefreshCounter();
  27141. continue;
  27142. }
  27143. mesh._preActivateForIntermediateRendering(sceneRenderId);
  27144. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  27145. mesh._activate(sceneRenderId);
  27146. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27147. var subMesh = mesh.subMeshes[subIndex];
  27148. scene._activeIndices.addCount(subMesh.indexCount, false);
  27149. this._renderingManager.dispatch(subMesh);
  27150. }
  27151. }
  27152. }
  27153. }
  27154. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  27155. var particleSystem = scene.particleSystems[particleIndex];
  27156. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  27157. continue;
  27158. }
  27159. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  27160. this._renderingManager.dispatchParticles(particleSystem);
  27161. }
  27162. }
  27163. if (this.isCube) {
  27164. for (var face = 0; face < 6; face++) {
  27165. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27166. scene.incrementRenderId();
  27167. scene.resetCachedMaterial();
  27168. }
  27169. }
  27170. else {
  27171. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27172. }
  27173. this.onAfterUnbindObservable.notifyObservers(this);
  27174. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  27175. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  27176. }
  27177. engine.setViewport(scene.activeCamera.viewport);
  27178. scene.resetCachedMaterial();
  27179. };
  27180. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  27181. var scene = this.getScene();
  27182. var engine = scene.getEngine();
  27183. // Bind
  27184. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  27185. if (this.isCube) {
  27186. engine.bindFramebuffer(this._texture, faceIndex);
  27187. }
  27188. else {
  27189. engine.bindFramebuffer(this._texture);
  27190. }
  27191. }
  27192. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27193. // Clear
  27194. if (this.onClearObservable.hasObservers()) {
  27195. this.onClearObservable.notifyObservers(engine);
  27196. }
  27197. else {
  27198. engine.clear(scene.clearColor, true, true, true);
  27199. }
  27200. if (!this._doNotChangeAspectRatio) {
  27201. scene.updateTransformMatrix(true);
  27202. }
  27203. // Render
  27204. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27205. if (useCameraPostProcess) {
  27206. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27207. }
  27208. if (!this._doNotChangeAspectRatio) {
  27209. scene.updateTransformMatrix(true);
  27210. }
  27211. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27212. // Dump ?
  27213. if (dumpForDebug) {
  27214. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27215. }
  27216. // Unbind
  27217. if (!this.isCube || faceIndex === 5) {
  27218. if (this.isCube) {
  27219. if (faceIndex === 5) {
  27220. engine.generateMipMapsForCubemap(this._texture);
  27221. }
  27222. }
  27223. engine.unBindFramebuffer(this._texture, this.isCube);
  27224. }
  27225. };
  27226. /**
  27227. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27228. * This allowed control for front to back rendering or reversly depending of the special needs.
  27229. *
  27230. * @param renderingGroupId The rendering group id corresponding to its index
  27231. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27232. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27233. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27234. */
  27235. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27236. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27237. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27238. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27239. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27240. };
  27241. /**
  27242. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27243. *
  27244. * @param renderingGroupId The rendering group id corresponding to its index
  27245. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27246. */
  27247. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27248. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27249. };
  27250. RenderTargetTexture.prototype.clone = function () {
  27251. var textureSize = this.getSize();
  27252. 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);
  27253. // Base texture
  27254. newTexture.hasAlpha = this.hasAlpha;
  27255. newTexture.level = this.level;
  27256. // RenderTarget Texture
  27257. newTexture.coordinatesMode = this.coordinatesMode;
  27258. newTexture.renderList = this.renderList.slice(0);
  27259. return newTexture;
  27260. };
  27261. RenderTargetTexture.prototype.serialize = function () {
  27262. if (!this.name) {
  27263. return null;
  27264. }
  27265. var serializationObject = _super.prototype.serialize.call(this);
  27266. serializationObject.renderTargetSize = this.getRenderSize();
  27267. serializationObject.renderList = [];
  27268. for (var index = 0; index < this.renderList.length; index++) {
  27269. serializationObject.renderList.push(this.renderList[index].id);
  27270. }
  27271. return serializationObject;
  27272. };
  27273. return RenderTargetTexture;
  27274. }(BABYLON.Texture));
  27275. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27276. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27277. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27278. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27279. })(BABYLON || (BABYLON = {}));
  27280. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27281. var BABYLON;
  27282. (function (BABYLON) {
  27283. var ProceduralTexture = (function (_super) {
  27284. __extends(ProceduralTexture, _super);
  27285. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27286. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27287. if (isCube === void 0) { isCube = false; }
  27288. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27289. _this.isCube = isCube;
  27290. _this.isEnabled = true;
  27291. _this._currentRefreshId = -1;
  27292. _this._refreshRate = 1;
  27293. _this._vertexBuffers = {};
  27294. _this._uniforms = new Array();
  27295. _this._samplers = new Array();
  27296. _this._textures = new Array();
  27297. _this._floats = new Array();
  27298. _this._floatsArrays = {};
  27299. _this._colors3 = new Array();
  27300. _this._colors4 = new Array();
  27301. _this._vectors2 = new Array();
  27302. _this._vectors3 = new Array();
  27303. _this._matrices = new Array();
  27304. _this._fallbackTextureUsed = false;
  27305. scene._proceduralTextures.push(_this);
  27306. _this.name = name;
  27307. _this.isRenderTarget = true;
  27308. _this._size = size;
  27309. _this._generateMipMaps = generateMipMaps;
  27310. _this.setFragment(fragment);
  27311. _this._fallbackTexture = fallbackTexture;
  27312. var engine = scene.getEngine();
  27313. if (isCube) {
  27314. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27315. _this.setFloat("face", 0);
  27316. }
  27317. else {
  27318. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27319. }
  27320. // VBO
  27321. var vertices = [];
  27322. vertices.push(1, 1);
  27323. vertices.push(-1, 1);
  27324. vertices.push(-1, -1);
  27325. vertices.push(1, -1);
  27326. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27327. // Indices
  27328. var indices = [];
  27329. indices.push(0);
  27330. indices.push(1);
  27331. indices.push(2);
  27332. indices.push(0);
  27333. indices.push(2);
  27334. indices.push(3);
  27335. _this._indexBuffer = engine.createIndexBuffer(indices);
  27336. return _this;
  27337. }
  27338. ProceduralTexture.prototype.reset = function () {
  27339. if (this._effect === undefined) {
  27340. return;
  27341. }
  27342. var engine = this.getScene().getEngine();
  27343. engine._releaseEffect(this._effect);
  27344. };
  27345. ProceduralTexture.prototype.isReady = function () {
  27346. var _this = this;
  27347. var engine = this.getScene().getEngine();
  27348. var shaders;
  27349. if (!this._fragment) {
  27350. return false;
  27351. }
  27352. if (this._fallbackTextureUsed) {
  27353. return true;
  27354. }
  27355. if (this._fragment.fragmentElement !== undefined) {
  27356. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27357. }
  27358. else {
  27359. shaders = { vertex: "procedural", fragment: this._fragment };
  27360. }
  27361. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27362. _this.releaseInternalTexture();
  27363. if (_this._fallbackTexture) {
  27364. _this._texture = _this._fallbackTexture._texture;
  27365. _this._texture.references++;
  27366. }
  27367. _this._fallbackTextureUsed = true;
  27368. });
  27369. return this._effect.isReady();
  27370. };
  27371. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27372. this._currentRefreshId = -1;
  27373. };
  27374. ProceduralTexture.prototype.setFragment = function (fragment) {
  27375. this._fragment = fragment;
  27376. };
  27377. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27378. get: function () {
  27379. return this._refreshRate;
  27380. },
  27381. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27382. set: function (value) {
  27383. this._refreshRate = value;
  27384. this.resetRefreshCounter();
  27385. },
  27386. enumerable: true,
  27387. configurable: true
  27388. });
  27389. ProceduralTexture.prototype._shouldRender = function () {
  27390. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27391. return false;
  27392. }
  27393. if (this._fallbackTextureUsed) {
  27394. return false;
  27395. }
  27396. if (this._currentRefreshId === -1) {
  27397. this._currentRefreshId = 1;
  27398. return true;
  27399. }
  27400. if (this.refreshRate === this._currentRefreshId) {
  27401. this._currentRefreshId = 1;
  27402. return true;
  27403. }
  27404. this._currentRefreshId++;
  27405. return false;
  27406. };
  27407. ProceduralTexture.prototype.getRenderSize = function () {
  27408. return this._size;
  27409. };
  27410. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27411. if (this._fallbackTextureUsed) {
  27412. return;
  27413. }
  27414. this.releaseInternalTexture();
  27415. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27416. };
  27417. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27418. if (this._uniforms.indexOf(uniformName) === -1) {
  27419. this._uniforms.push(uniformName);
  27420. }
  27421. };
  27422. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27423. if (this._samplers.indexOf(name) === -1) {
  27424. this._samplers.push(name);
  27425. }
  27426. this._textures[name] = texture;
  27427. return this;
  27428. };
  27429. ProceduralTexture.prototype.setFloat = function (name, value) {
  27430. this._checkUniform(name);
  27431. this._floats[name] = value;
  27432. return this;
  27433. };
  27434. ProceduralTexture.prototype.setFloats = function (name, value) {
  27435. this._checkUniform(name);
  27436. this._floatsArrays[name] = value;
  27437. return this;
  27438. };
  27439. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27440. this._checkUniform(name);
  27441. this._colors3[name] = value;
  27442. return this;
  27443. };
  27444. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27445. this._checkUniform(name);
  27446. this._colors4[name] = value;
  27447. return this;
  27448. };
  27449. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27450. this._checkUniform(name);
  27451. this._vectors2[name] = value;
  27452. return this;
  27453. };
  27454. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27455. this._checkUniform(name);
  27456. this._vectors3[name] = value;
  27457. return this;
  27458. };
  27459. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27460. this._checkUniform(name);
  27461. this._matrices[name] = value;
  27462. return this;
  27463. };
  27464. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27465. var scene = this.getScene();
  27466. var engine = scene.getEngine();
  27467. // Render
  27468. engine.enableEffect(this._effect);
  27469. engine.setState(false);
  27470. // Texture
  27471. for (var name in this._textures) {
  27472. this._effect.setTexture(name, this._textures[name]);
  27473. }
  27474. // Float
  27475. for (name in this._floats) {
  27476. this._effect.setFloat(name, this._floats[name]);
  27477. }
  27478. // Floats
  27479. for (name in this._floatsArrays) {
  27480. this._effect.setArray(name, this._floatsArrays[name]);
  27481. }
  27482. // Color3
  27483. for (name in this._colors3) {
  27484. this._effect.setColor3(name, this._colors3[name]);
  27485. }
  27486. // Color4
  27487. for (name in this._colors4) {
  27488. var color = this._colors4[name];
  27489. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  27490. }
  27491. // Vector2
  27492. for (name in this._vectors2) {
  27493. this._effect.setVector2(name, this._vectors2[name]);
  27494. }
  27495. // Vector3
  27496. for (name in this._vectors3) {
  27497. this._effect.setVector3(name, this._vectors3[name]);
  27498. }
  27499. // Matrix
  27500. for (name in this._matrices) {
  27501. this._effect.setMatrix(name, this._matrices[name]);
  27502. }
  27503. if (this.isCube) {
  27504. for (var face = 0; face < 6; face++) {
  27505. engine.bindFramebuffer(this._texture, face);
  27506. // VBOs
  27507. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27508. this._effect.setFloat("face", face);
  27509. // Clear
  27510. engine.clear(scene.clearColor, true, true, true);
  27511. // Draw order
  27512. engine.draw(true, 0, 6);
  27513. // Mipmaps
  27514. if (face === 5) {
  27515. engine.generateMipMapsForCubemap(this._texture);
  27516. }
  27517. }
  27518. }
  27519. else {
  27520. engine.bindFramebuffer(this._texture);
  27521. // VBOs
  27522. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  27523. // Clear
  27524. engine.clear(scene.clearColor, true, true, true);
  27525. // Draw order
  27526. engine.draw(true, 0, 6);
  27527. }
  27528. // Unbind
  27529. engine.unBindFramebuffer(this._texture, this.isCube);
  27530. if (this.onGenerated) {
  27531. this.onGenerated();
  27532. }
  27533. };
  27534. ProceduralTexture.prototype.clone = function () {
  27535. var textureSize = this.getSize();
  27536. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  27537. // Base texture
  27538. newTexture.hasAlpha = this.hasAlpha;
  27539. newTexture.level = this.level;
  27540. // RenderTarget Texture
  27541. newTexture.coordinatesMode = this.coordinatesMode;
  27542. return newTexture;
  27543. };
  27544. ProceduralTexture.prototype.dispose = function () {
  27545. var index = this.getScene()._proceduralTextures.indexOf(this);
  27546. if (index >= 0) {
  27547. this.getScene()._proceduralTextures.splice(index, 1);
  27548. }
  27549. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27550. if (vertexBuffer) {
  27551. vertexBuffer.dispose();
  27552. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27553. }
  27554. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  27555. this._indexBuffer = null;
  27556. }
  27557. _super.prototype.dispose.call(this);
  27558. };
  27559. return ProceduralTexture;
  27560. }(BABYLON.Texture));
  27561. BABYLON.ProceduralTexture = ProceduralTexture;
  27562. })(BABYLON || (BABYLON = {}));
  27563. //# sourceMappingURL=babylon.proceduralTexture.js.map
  27564. /// <reference path="babylon.renderTargetTexture.ts" />
  27565. var BABYLON;
  27566. (function (BABYLON) {
  27567. var MirrorTexture = (function (_super) {
  27568. __extends(MirrorTexture, _super);
  27569. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  27570. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27571. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27572. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27573. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  27574. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  27575. _this._transformMatrix = BABYLON.Matrix.Zero();
  27576. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  27577. _this.onBeforeRenderObservable.add(function () {
  27578. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  27579. _this._savedViewMatrix = scene.getViewMatrix();
  27580. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  27581. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  27582. scene.clipPlane = _this.mirrorPlane;
  27583. scene.getEngine().cullBackFaces = false;
  27584. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  27585. });
  27586. _this.onAfterRenderObservable.add(function () {
  27587. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  27588. scene.getEngine().cullBackFaces = true;
  27589. scene._mirroredCameraPosition = null;
  27590. delete scene.clipPlane;
  27591. });
  27592. return _this;
  27593. }
  27594. MirrorTexture.prototype.clone = function () {
  27595. var textureSize = this.getSize();
  27596. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  27597. // Base texture
  27598. newTexture.hasAlpha = this.hasAlpha;
  27599. newTexture.level = this.level;
  27600. // Mirror Texture
  27601. newTexture.mirrorPlane = this.mirrorPlane.clone();
  27602. newTexture.renderList = this.renderList.slice(0);
  27603. return newTexture;
  27604. };
  27605. MirrorTexture.prototype.serialize = function () {
  27606. if (!this.name) {
  27607. return null;
  27608. }
  27609. var serializationObject = _super.prototype.serialize.call(this);
  27610. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  27611. return serializationObject;
  27612. };
  27613. return MirrorTexture;
  27614. }(BABYLON.RenderTargetTexture));
  27615. BABYLON.MirrorTexture = MirrorTexture;
  27616. })(BABYLON || (BABYLON = {}));
  27617. //# sourceMappingURL=babylon.mirrorTexture.js.map
  27618. /// <reference path="babylon.renderTargetTexture.ts" />
  27619. var BABYLON;
  27620. (function (BABYLON) {
  27621. /**
  27622. * Creates a refraction texture used by refraction channel of the standard material.
  27623. * @param name the texture name
  27624. * @param size size of the underlying texture
  27625. * @param scene root scene
  27626. */
  27627. var RefractionTexture = (function (_super) {
  27628. __extends(RefractionTexture, _super);
  27629. function RefractionTexture(name, size, scene, generateMipMaps) {
  27630. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  27631. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  27632. _this.depth = 2.0;
  27633. _this.onBeforeRenderObservable.add(function () {
  27634. scene.clipPlane = _this.refractionPlane;
  27635. });
  27636. _this.onAfterRenderObservable.add(function () {
  27637. delete scene.clipPlane;
  27638. });
  27639. return _this;
  27640. }
  27641. RefractionTexture.prototype.clone = function () {
  27642. var textureSize = this.getSize();
  27643. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  27644. // Base texture
  27645. newTexture.hasAlpha = this.hasAlpha;
  27646. newTexture.level = this.level;
  27647. // Refraction Texture
  27648. newTexture.refractionPlane = this.refractionPlane.clone();
  27649. newTexture.renderList = this.renderList.slice(0);
  27650. newTexture.depth = this.depth;
  27651. return newTexture;
  27652. };
  27653. RefractionTexture.prototype.serialize = function () {
  27654. if (!this.name) {
  27655. return null;
  27656. }
  27657. var serializationObject = _super.prototype.serialize.call(this);
  27658. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  27659. serializationObject.depth = this.depth;
  27660. return serializationObject;
  27661. };
  27662. return RefractionTexture;
  27663. }(BABYLON.RenderTargetTexture));
  27664. BABYLON.RefractionTexture = RefractionTexture;
  27665. })(BABYLON || (BABYLON = {}));
  27666. //# sourceMappingURL=babylon.refractionTexture.js.map
  27667. /// <reference path="babylon.texture.ts" />
  27668. var BABYLON;
  27669. (function (BABYLON) {
  27670. var DynamicTexture = (function (_super) {
  27671. __extends(DynamicTexture, _super);
  27672. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  27673. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27674. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27675. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  27676. _this.name = name;
  27677. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27678. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27679. _this._generateMipMaps = generateMipMaps;
  27680. if (options.getContext) {
  27681. _this._canvas = options;
  27682. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27683. }
  27684. else {
  27685. _this._canvas = document.createElement("canvas");
  27686. if (options.width) {
  27687. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  27688. }
  27689. else {
  27690. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  27691. }
  27692. }
  27693. var textureSize = _this.getSize();
  27694. _this._canvas.width = textureSize.width;
  27695. _this._canvas.height = textureSize.height;
  27696. _this._context = _this._canvas.getContext("2d");
  27697. return _this;
  27698. }
  27699. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  27700. get: function () {
  27701. return true;
  27702. },
  27703. enumerable: true,
  27704. configurable: true
  27705. });
  27706. DynamicTexture.prototype.scale = function (ratio) {
  27707. var textureSize = this.getSize();
  27708. textureSize.width *= ratio;
  27709. textureSize.height *= ratio;
  27710. this._canvas.width = textureSize.width;
  27711. this._canvas.height = textureSize.height;
  27712. this.releaseInternalTexture();
  27713. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  27714. };
  27715. DynamicTexture.prototype.getContext = function () {
  27716. return this._context;
  27717. };
  27718. DynamicTexture.prototype.clear = function () {
  27719. var size = this.getSize();
  27720. this._context.fillRect(0, 0, size.width, size.height);
  27721. };
  27722. DynamicTexture.prototype.update = function (invertY) {
  27723. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  27724. };
  27725. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  27726. if (update === void 0) { update = true; }
  27727. var size = this.getSize();
  27728. if (clearColor) {
  27729. this._context.fillStyle = clearColor;
  27730. this._context.fillRect(0, 0, size.width, size.height);
  27731. }
  27732. this._context.font = font;
  27733. if (x === null) {
  27734. var textSize = this._context.measureText(text);
  27735. x = (size.width - textSize.width) / 2;
  27736. }
  27737. this._context.fillStyle = color;
  27738. this._context.fillText(text, x, y);
  27739. if (update) {
  27740. this.update(invertY);
  27741. }
  27742. };
  27743. DynamicTexture.prototype.clone = function () {
  27744. var textureSize = this.getSize();
  27745. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  27746. // Base texture
  27747. newTexture.hasAlpha = this.hasAlpha;
  27748. newTexture.level = this.level;
  27749. // Dynamic Texture
  27750. newTexture.wrapU = this.wrapU;
  27751. newTexture.wrapV = this.wrapV;
  27752. return newTexture;
  27753. };
  27754. return DynamicTexture;
  27755. }(BABYLON.Texture));
  27756. BABYLON.DynamicTexture = DynamicTexture;
  27757. })(BABYLON || (BABYLON = {}));
  27758. //# sourceMappingURL=babylon.dynamicTexture.js.map
  27759. var BABYLON;
  27760. (function (BABYLON) {
  27761. var VideoTexture = (function (_super) {
  27762. __extends(VideoTexture, _super);
  27763. /**
  27764. * Creates a video texture.
  27765. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  27766. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  27767. * @param {BABYLON.Scene} scene is obviously the current scene.
  27768. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  27769. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  27770. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  27771. */
  27772. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  27773. if (generateMipMaps === void 0) { generateMipMaps = false; }
  27774. if (invertY === void 0) { invertY = false; }
  27775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27776. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  27777. _this._autoLaunch = true;
  27778. var urls;
  27779. _this.name = name;
  27780. if (urlsOrVideo instanceof HTMLVideoElement) {
  27781. _this.video = urlsOrVideo;
  27782. }
  27783. else {
  27784. urls = urlsOrVideo;
  27785. _this.video = document.createElement("video");
  27786. _this.video.autoplay = false;
  27787. _this.video.loop = true;
  27788. }
  27789. _this._generateMipMaps = generateMipMaps;
  27790. _this._samplingMode = samplingMode;
  27791. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  27792. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27793. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27794. }
  27795. else {
  27796. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27797. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27798. _this._generateMipMaps = false;
  27799. }
  27800. if (urls) {
  27801. _this.video.addEventListener("canplaythrough", function () {
  27802. _this._createTexture();
  27803. });
  27804. urls.forEach(function (url) {
  27805. var source = document.createElement("source");
  27806. source.src = url;
  27807. _this.video.appendChild(source);
  27808. });
  27809. }
  27810. else {
  27811. _this._createTexture();
  27812. }
  27813. _this._lastUpdate = BABYLON.Tools.Now;
  27814. return _this;
  27815. }
  27816. VideoTexture.prototype._createTexture = function () {
  27817. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  27818. this._texture.isReady = true;
  27819. };
  27820. VideoTexture.prototype.update = function () {
  27821. if (this._autoLaunch) {
  27822. this._autoLaunch = false;
  27823. this.video.play();
  27824. }
  27825. var now = BABYLON.Tools.Now;
  27826. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  27827. return false;
  27828. }
  27829. this._lastUpdate = now;
  27830. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  27831. return true;
  27832. };
  27833. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  27834. var video = document.createElement("video");
  27835. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  27836. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  27837. if (navigator.getUserMedia) {
  27838. navigator.getUserMedia({
  27839. video: {
  27840. width: {
  27841. min: (constraints && constraints.minWidth) || 256,
  27842. max: (constraints && constraints.maxWidth) || 640
  27843. },
  27844. height: {
  27845. min: (constraints && constraints.minHeight) || 256,
  27846. max: (constraints && constraints.maxHeight) || 480
  27847. }
  27848. }
  27849. }, function (stream) {
  27850. if (video.mozSrcObject !== undefined) {
  27851. video.mozSrcObject = stream;
  27852. }
  27853. else {
  27854. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  27855. }
  27856. video.play();
  27857. if (onReady) {
  27858. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  27859. }
  27860. }, function (e) {
  27861. BABYLON.Tools.Error(e.name);
  27862. });
  27863. }
  27864. };
  27865. return VideoTexture;
  27866. }(BABYLON.Texture));
  27867. BABYLON.VideoTexture = VideoTexture;
  27868. })(BABYLON || (BABYLON = {}));
  27869. //# sourceMappingURL=babylon.videoTexture.js.map
  27870. /// <reference path="babylon.proceduralTexture.ts" />
  27871. var BABYLON;
  27872. (function (BABYLON) {
  27873. var CustomProceduralTexture = (function (_super) {
  27874. __extends(CustomProceduralTexture, _super);
  27875. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  27876. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  27877. _this._animate = true;
  27878. _this._time = 0;
  27879. _this._texturePath = texturePath;
  27880. //Try to load json
  27881. _this.loadJson(texturePath);
  27882. _this.refreshRate = 1;
  27883. return _this;
  27884. }
  27885. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  27886. var _this = this;
  27887. var that = this;
  27888. function noConfigFile() {
  27889. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  27890. try {
  27891. that.setFragment(that._texturePath);
  27892. }
  27893. catch (ex) {
  27894. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  27895. }
  27896. }
  27897. var configFileUrl = jsonUrl + "/config.json";
  27898. var xhr = new XMLHttpRequest();
  27899. xhr.open("GET", configFileUrl, true);
  27900. xhr.addEventListener("load", function () {
  27901. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  27902. try {
  27903. _this._config = JSON.parse(xhr.response);
  27904. _this.updateShaderUniforms();
  27905. _this.updateTextures();
  27906. _this.setFragment(_this._texturePath + "/custom");
  27907. _this._animate = _this._config.animate;
  27908. _this.refreshRate = _this._config.refreshrate;
  27909. }
  27910. catch (ex) {
  27911. noConfigFile();
  27912. }
  27913. }
  27914. else {
  27915. noConfigFile();
  27916. }
  27917. }, false);
  27918. xhr.addEventListener("error", function () {
  27919. noConfigFile();
  27920. }, false);
  27921. try {
  27922. xhr.send();
  27923. }
  27924. catch (ex) {
  27925. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  27926. }
  27927. };
  27928. CustomProceduralTexture.prototype.isReady = function () {
  27929. if (!_super.prototype.isReady.call(this)) {
  27930. return false;
  27931. }
  27932. for (var name in this._textures) {
  27933. var texture = this._textures[name];
  27934. if (!texture.isReady()) {
  27935. return false;
  27936. }
  27937. }
  27938. return true;
  27939. };
  27940. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  27941. if (this._animate) {
  27942. this._time += this.getScene().getAnimationRatio() * 0.03;
  27943. this.updateShaderUniforms();
  27944. }
  27945. _super.prototype.render.call(this, useCameraPostProcess);
  27946. };
  27947. CustomProceduralTexture.prototype.updateTextures = function () {
  27948. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  27949. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  27950. }
  27951. };
  27952. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  27953. if (this._config) {
  27954. for (var j = 0; j < this._config.uniforms.length; j++) {
  27955. var uniform = this._config.uniforms[j];
  27956. switch (uniform.type) {
  27957. case "float":
  27958. this.setFloat(uniform.name, uniform.value);
  27959. break;
  27960. case "color3":
  27961. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  27962. break;
  27963. case "color4":
  27964. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  27965. break;
  27966. case "vector2":
  27967. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  27968. break;
  27969. case "vector3":
  27970. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  27971. break;
  27972. }
  27973. }
  27974. }
  27975. this.setFloat("time", this._time);
  27976. };
  27977. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  27978. get: function () {
  27979. return this._animate;
  27980. },
  27981. set: function (value) {
  27982. this._animate = value;
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. return CustomProceduralTexture;
  27988. }(BABYLON.ProceduralTexture));
  27989. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  27990. })(BABYLON || (BABYLON = {}));
  27991. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  27992. var BABYLON;
  27993. (function (BABYLON) {
  27994. var EffectFallbacks = (function () {
  27995. function EffectFallbacks() {
  27996. this._defines = {};
  27997. this._currentRank = 32;
  27998. this._maxRank = -1;
  27999. }
  28000. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28001. if (!this._defines[rank]) {
  28002. if (rank < this._currentRank) {
  28003. this._currentRank = rank;
  28004. }
  28005. if (rank > this._maxRank) {
  28006. this._maxRank = rank;
  28007. }
  28008. this._defines[rank] = new Array();
  28009. }
  28010. this._defines[rank].push(define);
  28011. };
  28012. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  28013. this._meshRank = rank;
  28014. this._mesh = mesh;
  28015. if (rank < this._currentRank) {
  28016. this._currentRank = rank;
  28017. }
  28018. if (rank > this._maxRank) {
  28019. this._maxRank = rank;
  28020. }
  28021. };
  28022. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  28023. get: function () {
  28024. return this._currentRank <= this._maxRank;
  28025. },
  28026. enumerable: true,
  28027. configurable: true
  28028. });
  28029. EffectFallbacks.prototype.reduce = function (currentDefines) {
  28030. var currentFallbacks = this._defines[this._currentRank];
  28031. if (currentFallbacks) {
  28032. for (var index = 0; index < currentFallbacks.length; index++) {
  28033. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  28034. }
  28035. }
  28036. if (this._mesh && this._currentRank === this._meshRank) {
  28037. this._mesh.computeBonesUsingShaders = false;
  28038. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  28039. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  28040. }
  28041. this._currentRank++;
  28042. return currentDefines;
  28043. };
  28044. return EffectFallbacks;
  28045. }());
  28046. BABYLON.EffectFallbacks = EffectFallbacks;
  28047. var Effect = (function () {
  28048. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  28049. var _this = this;
  28050. this.uniqueId = 0;
  28051. this._isReady = false;
  28052. this._compilationError = "";
  28053. this._valueCache = {};
  28054. this._engine = engine;
  28055. this.name = baseName;
  28056. this.defines = defines;
  28057. this._uniformsNames = uniformsNames.concat(samplers);
  28058. this._samplers = samplers;
  28059. this._attributesNames = attributesNames;
  28060. this.onError = onError;
  28061. this.onCompiled = onCompiled;
  28062. this._indexParameters = indexParameters;
  28063. this.uniqueId = Effect._uniqueIdSeed++;
  28064. var vertexSource;
  28065. var fragmentSource;
  28066. if (baseName.vertexElement) {
  28067. vertexSource = document.getElementById(baseName.vertexElement);
  28068. if (!vertexSource) {
  28069. vertexSource = baseName.vertexElement;
  28070. }
  28071. }
  28072. else {
  28073. vertexSource = baseName.vertex || baseName;
  28074. }
  28075. if (baseName.fragmentElement) {
  28076. fragmentSource = document.getElementById(baseName.fragmentElement);
  28077. if (!fragmentSource) {
  28078. fragmentSource = baseName.fragmentElement;
  28079. }
  28080. }
  28081. else {
  28082. fragmentSource = baseName.fragment || baseName;
  28083. }
  28084. this._loadVertexShader(vertexSource, function (vertexCode) {
  28085. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  28086. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  28087. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  28088. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  28089. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  28090. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  28091. });
  28092. });
  28093. });
  28094. });
  28095. });
  28096. });
  28097. }
  28098. Object.defineProperty(Effect.prototype, "key", {
  28099. get: function () {
  28100. return this._key;
  28101. },
  28102. enumerable: true,
  28103. configurable: true
  28104. });
  28105. // Properties
  28106. Effect.prototype.isReady = function () {
  28107. return this._isReady;
  28108. };
  28109. Effect.prototype.getProgram = function () {
  28110. return this._program;
  28111. };
  28112. Effect.prototype.getAttributesNames = function () {
  28113. return this._attributesNames;
  28114. };
  28115. Effect.prototype.getAttributeLocation = function (index) {
  28116. return this._attributes[index];
  28117. };
  28118. Effect.prototype.getAttributeLocationByName = function (name) {
  28119. var index = this._attributesNames.indexOf(name);
  28120. return this._attributes[index];
  28121. };
  28122. Effect.prototype.getAttributesCount = function () {
  28123. return this._attributes.length;
  28124. };
  28125. Effect.prototype.getUniformIndex = function (uniformName) {
  28126. return this._uniformsNames.indexOf(uniformName);
  28127. };
  28128. Effect.prototype.getUniform = function (uniformName) {
  28129. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  28130. };
  28131. Effect.prototype.getSamplers = function () {
  28132. return this._samplers;
  28133. };
  28134. Effect.prototype.getCompilationError = function () {
  28135. return this._compilationError;
  28136. };
  28137. Effect.prototype.getVertexShaderSource = function () {
  28138. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  28139. };
  28140. Effect.prototype.getFragmentShaderSource = function () {
  28141. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  28142. };
  28143. // Methods
  28144. Effect.prototype._loadVertexShader = function (vertex, callback) {
  28145. // DOM element ?
  28146. if (vertex instanceof HTMLElement) {
  28147. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  28148. callback(vertexCode);
  28149. return;
  28150. }
  28151. // Base64 encoded ?
  28152. if (vertex.substr(0, 7) === "base64:") {
  28153. var vertexBinary = window.atob(vertex.substr(7));
  28154. callback(vertexBinary);
  28155. return;
  28156. }
  28157. // Is in local store ?
  28158. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  28159. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  28160. return;
  28161. }
  28162. var vertexShaderUrl;
  28163. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  28164. vertexShaderUrl = vertex;
  28165. }
  28166. else {
  28167. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  28168. }
  28169. // Vertex shader
  28170. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  28171. };
  28172. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  28173. // DOM element ?
  28174. if (fragment instanceof HTMLElement) {
  28175. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  28176. callback(fragmentCode);
  28177. return;
  28178. }
  28179. // Base64 encoded ?
  28180. if (fragment.substr(0, 7) === "base64:") {
  28181. var fragmentBinary = window.atob(fragment.substr(7));
  28182. callback(fragmentBinary);
  28183. return;
  28184. }
  28185. // Is in local store ?
  28186. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  28187. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  28188. return;
  28189. }
  28190. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  28191. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28192. return;
  28193. }
  28194. var fragmentShaderUrl;
  28195. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28196. fragmentShaderUrl = fragment;
  28197. }
  28198. else {
  28199. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28200. }
  28201. // Fragment shader
  28202. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28203. };
  28204. Effect.prototype._dumpShadersName = function () {
  28205. if (this.name.vertexElement) {
  28206. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28207. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28208. }
  28209. else if (this.name.vertex) {
  28210. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28211. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28212. }
  28213. else {
  28214. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28215. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28216. }
  28217. };
  28218. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28219. var preparedSourceCode = this._processPrecision(sourceCode);
  28220. if (this._engine.webGLVersion == 1) {
  28221. callback(preparedSourceCode);
  28222. return;
  28223. }
  28224. // Already converted
  28225. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28226. callback(preparedSourceCode);
  28227. return;
  28228. }
  28229. // Remove extensions
  28230. // #extension GL_OES_standard_derivatives : enable
  28231. // #extension GL_EXT_shader_texture_lod : enable
  28232. // #extension GL_EXT_frag_depth : enable
  28233. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28234. var result = preparedSourceCode.replace(regex, "");
  28235. // Migrate to GLSL v300
  28236. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28237. result = result.replace(/attribute[ \t]/g, "in ");
  28238. result = result.replace(/[ \t]attribute/g, " in");
  28239. if (isFragment) {
  28240. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  28241. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28242. result = result.replace(/texture2D\(/g, "texture(");
  28243. result = result.replace(/textureCube\(/g, "texture(");
  28244. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28245. result = result.replace(/gl_FragColor/g, "glFragColor");
  28246. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28247. }
  28248. callback(result);
  28249. };
  28250. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28251. var _this = this;
  28252. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28253. var match = regex.exec(sourceCode);
  28254. var returnValue = new String(sourceCode);
  28255. while (match != null) {
  28256. var includeFile = match[1];
  28257. if (Effect.IncludesShadersStore[includeFile]) {
  28258. // Substitution
  28259. var includeContent = Effect.IncludesShadersStore[includeFile];
  28260. if (match[2]) {
  28261. var splits = match[3].split(",");
  28262. for (var index = 0; index < splits.length; index += 2) {
  28263. var source = new RegExp(splits[index], "g");
  28264. var dest = splits[index + 1];
  28265. includeContent = includeContent.replace(source, dest);
  28266. }
  28267. }
  28268. if (match[4]) {
  28269. var indexString = match[5];
  28270. if (indexString.indexOf("..") !== -1) {
  28271. var indexSplits = indexString.split("..");
  28272. var minIndex = parseInt(indexSplits[0]);
  28273. var maxIndex = parseInt(indexSplits[1]);
  28274. var sourceIncludeContent = includeContent.slice(0);
  28275. includeContent = "";
  28276. if (isNaN(maxIndex)) {
  28277. maxIndex = this._indexParameters[indexSplits[1]];
  28278. }
  28279. for (var i = minIndex; i <= maxIndex; i++) {
  28280. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28281. }
  28282. }
  28283. else {
  28284. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28285. }
  28286. }
  28287. // Replace
  28288. returnValue = returnValue.replace(match[0], includeContent);
  28289. }
  28290. else {
  28291. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28292. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28293. Effect.IncludesShadersStore[includeFile] = fileContent;
  28294. _this._processIncludes(returnValue, callback);
  28295. });
  28296. return;
  28297. }
  28298. match = regex.exec(sourceCode);
  28299. }
  28300. callback(returnValue);
  28301. };
  28302. Effect.prototype._processPrecision = function (source) {
  28303. if (source.indexOf("precision highp float") === -1) {
  28304. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28305. source = "precision mediump float;\n" + source;
  28306. }
  28307. else {
  28308. source = "precision highp float;\n" + source;
  28309. }
  28310. }
  28311. else {
  28312. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28313. source = source.replace("precision highp float", "precision mediump float");
  28314. }
  28315. }
  28316. return source;
  28317. };
  28318. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28319. try {
  28320. var engine = this._engine;
  28321. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28322. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28323. this._attributes = engine.getAttributes(this._program, attributesNames);
  28324. var index;
  28325. for (index = 0; index < this._samplers.length; index++) {
  28326. var sampler = this.getUniform(this._samplers[index]);
  28327. if (sampler == null) {
  28328. this._samplers.splice(index, 1);
  28329. index--;
  28330. }
  28331. }
  28332. engine.bindSamplers(this);
  28333. this._compilationError = "";
  28334. this._isReady = true;
  28335. if (this.onCompiled) {
  28336. this.onCompiled(this);
  28337. }
  28338. }
  28339. catch (e) {
  28340. this._compilationError = e.message;
  28341. // Let's go through fallbacks then
  28342. BABYLON.Tools.Error("Unable to compile effect: ");
  28343. BABYLON.Tools.Error("Defines: " + defines);
  28344. BABYLON.Tools.Error("Error: " + this._compilationError);
  28345. this._dumpShadersName();
  28346. if (fallbacks && fallbacks.isMoreFallbacks) {
  28347. BABYLON.Tools.Error("Trying next fallback.");
  28348. defines = fallbacks.reduce(defines);
  28349. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28350. }
  28351. else {
  28352. if (this.onError) {
  28353. this.onError(this, this._compilationError);
  28354. }
  28355. }
  28356. }
  28357. };
  28358. Object.defineProperty(Effect.prototype, "isSupported", {
  28359. get: function () {
  28360. return this._compilationError === "";
  28361. },
  28362. enumerable: true,
  28363. configurable: true
  28364. });
  28365. Effect.prototype._bindTexture = function (channel, texture) {
  28366. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28367. };
  28368. Effect.prototype.setTexture = function (channel, texture) {
  28369. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28370. };
  28371. Effect.prototype.setTextureArray = function (channel, textures) {
  28372. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28373. var initialPos = this._samplers.indexOf(channel);
  28374. for (var index = 1; index < textures.length; index++) {
  28375. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28376. }
  28377. }
  28378. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28379. };
  28380. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28381. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28382. };
  28383. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28384. var changed = false;
  28385. var cache = this._valueCache[uniformName];
  28386. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28387. changed = true;
  28388. cache = new BABYLON.Matrix();
  28389. }
  28390. var tm = cache.m;
  28391. var om = matrix.m;
  28392. for (var index = 0; index < 16; index++) {
  28393. if (tm[index] !== om[index]) {
  28394. tm[index] = om[index];
  28395. changed = true;
  28396. }
  28397. }
  28398. this._valueCache[uniformName] = cache;
  28399. return changed;
  28400. };
  28401. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28402. var cache = this._valueCache[uniformName];
  28403. if (!cache) {
  28404. cache = [x, y];
  28405. this._valueCache[uniformName] = cache;
  28406. return true;
  28407. }
  28408. var changed = false;
  28409. if (cache[0] !== x) {
  28410. cache[0] = x;
  28411. changed = true;
  28412. }
  28413. if (cache[1] !== y) {
  28414. cache[1] = y;
  28415. changed = true;
  28416. }
  28417. return changed;
  28418. };
  28419. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28420. var cache = this._valueCache[uniformName];
  28421. if (!cache) {
  28422. cache = [x, y, z];
  28423. this._valueCache[uniformName] = cache;
  28424. return true;
  28425. }
  28426. var changed = false;
  28427. if (cache[0] !== x) {
  28428. cache[0] = x;
  28429. changed = true;
  28430. }
  28431. if (cache[1] !== y) {
  28432. cache[1] = y;
  28433. changed = true;
  28434. }
  28435. if (cache[2] !== z) {
  28436. cache[2] = z;
  28437. changed = true;
  28438. }
  28439. return changed;
  28440. };
  28441. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  28442. var cache = this._valueCache[uniformName];
  28443. if (!cache) {
  28444. cache = [x, y, z, w];
  28445. this._valueCache[uniformName] = cache;
  28446. return true;
  28447. }
  28448. var changed = false;
  28449. if (cache[0] !== x) {
  28450. cache[0] = x;
  28451. changed = true;
  28452. }
  28453. if (cache[1] !== y) {
  28454. cache[1] = y;
  28455. changed = true;
  28456. }
  28457. if (cache[2] !== z) {
  28458. cache[2] = z;
  28459. changed = true;
  28460. }
  28461. if (cache[3] !== w) {
  28462. cache[3] = w;
  28463. changed = true;
  28464. }
  28465. return changed;
  28466. };
  28467. Effect.prototype.setIntArray = function (uniformName, array) {
  28468. this._valueCache[uniformName] = null;
  28469. this._engine.setIntArray(this.getUniform(uniformName), array);
  28470. return this;
  28471. };
  28472. Effect.prototype.setIntArray2 = function (uniformName, array) {
  28473. this._valueCache[uniformName] = null;
  28474. this._engine.setIntArray2(this.getUniform(uniformName), array);
  28475. return this;
  28476. };
  28477. Effect.prototype.setIntArray3 = function (uniformName, array) {
  28478. this._valueCache[uniformName] = null;
  28479. this._engine.setIntArray3(this.getUniform(uniformName), array);
  28480. return this;
  28481. };
  28482. Effect.prototype.setIntArray4 = function (uniformName, array) {
  28483. this._valueCache[uniformName] = null;
  28484. this._engine.setIntArray4(this.getUniform(uniformName), array);
  28485. return this;
  28486. };
  28487. Effect.prototype.setFloatArray = function (uniformName, array) {
  28488. this._valueCache[uniformName] = null;
  28489. this._engine.setFloatArray(this.getUniform(uniformName), array);
  28490. return this;
  28491. };
  28492. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  28493. this._valueCache[uniformName] = null;
  28494. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  28495. return this;
  28496. };
  28497. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  28498. this._valueCache[uniformName] = null;
  28499. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  28500. return this;
  28501. };
  28502. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  28503. this._valueCache[uniformName] = null;
  28504. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  28505. return this;
  28506. };
  28507. Effect.prototype.setArray = function (uniformName, array) {
  28508. this._valueCache[uniformName] = null;
  28509. this._engine.setArray(this.getUniform(uniformName), array);
  28510. return this;
  28511. };
  28512. Effect.prototype.setArray2 = function (uniformName, array) {
  28513. this._valueCache[uniformName] = null;
  28514. this._engine.setArray2(this.getUniform(uniformName), array);
  28515. return this;
  28516. };
  28517. Effect.prototype.setArray3 = function (uniformName, array) {
  28518. this._valueCache[uniformName] = null;
  28519. this._engine.setArray3(this.getUniform(uniformName), array);
  28520. return this;
  28521. };
  28522. Effect.prototype.setArray4 = function (uniformName, array) {
  28523. this._valueCache[uniformName] = null;
  28524. this._engine.setArray4(this.getUniform(uniformName), array);
  28525. return this;
  28526. };
  28527. Effect.prototype.setMatrices = function (uniformName, matrices) {
  28528. this._valueCache[uniformName] = null;
  28529. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  28530. return this;
  28531. };
  28532. Effect.prototype.setMatrix = function (uniformName, matrix) {
  28533. if (this._cacheMatrix(uniformName, matrix)) {
  28534. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  28535. }
  28536. return this;
  28537. };
  28538. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  28539. this._valueCache[uniformName] = null;
  28540. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  28541. return this;
  28542. };
  28543. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  28544. this._valueCache[uniformName] = null;
  28545. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  28546. return this;
  28547. };
  28548. Effect.prototype.setFloat = function (uniformName, value) {
  28549. var cache = this._valueCache[uniformName];
  28550. if (cache !== undefined && cache === value)
  28551. return this;
  28552. this._valueCache[uniformName] = value;
  28553. this._engine.setFloat(this.getUniform(uniformName), value);
  28554. return this;
  28555. };
  28556. Effect.prototype.setBool = function (uniformName, bool) {
  28557. var cache = this._valueCache[uniformName];
  28558. if (cache !== undefined && cache === bool)
  28559. return this;
  28560. this._valueCache[uniformName] = bool;
  28561. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  28562. return this;
  28563. };
  28564. Effect.prototype.setVector2 = function (uniformName, vector2) {
  28565. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  28566. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  28567. }
  28568. return this;
  28569. };
  28570. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  28571. if (this._cacheFloat2(uniformName, x, y)) {
  28572. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  28573. }
  28574. return this;
  28575. };
  28576. Effect.prototype.setVector3 = function (uniformName, vector3) {
  28577. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  28578. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  28579. }
  28580. return this;
  28581. };
  28582. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  28583. if (this._cacheFloat3(uniformName, x, y, z)) {
  28584. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  28585. }
  28586. return this;
  28587. };
  28588. Effect.prototype.setVector4 = function (uniformName, vector4) {
  28589. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  28590. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  28591. }
  28592. return this;
  28593. };
  28594. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  28595. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  28596. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  28597. }
  28598. return this;
  28599. };
  28600. Effect.prototype.setColor3 = function (uniformName, color3) {
  28601. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  28602. this._engine.setColor3(this.getUniform(uniformName), color3);
  28603. }
  28604. return this;
  28605. };
  28606. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  28607. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  28608. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  28609. }
  28610. return this;
  28611. };
  28612. Effect.prototype._recombineShader = function (node) {
  28613. if (node.define) {
  28614. if (node.condition) {
  28615. var defineIndex = this.defines.indexOf("#define " + node.define);
  28616. if (defineIndex === -1) {
  28617. return null;
  28618. }
  28619. var nextComma = this.defines.indexOf("\n", defineIndex);
  28620. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  28621. var condition = defineValue + node.condition;
  28622. if (!eval(condition)) {
  28623. return null;
  28624. }
  28625. }
  28626. else if (node.ndef) {
  28627. if (this.defines.indexOf("#define " + node.define) !== -1) {
  28628. return null;
  28629. }
  28630. }
  28631. else if (this.defines.indexOf("#define " + node.define) === -1) {
  28632. return null;
  28633. }
  28634. }
  28635. var result = "";
  28636. for (var index = 0; index < node.children.length; index++) {
  28637. var line = node.children[index];
  28638. if (line.children) {
  28639. var combined = this._recombineShader(line);
  28640. if (combined !== null) {
  28641. result += combined + "\r\n";
  28642. }
  28643. continue;
  28644. }
  28645. if (line.length > 0) {
  28646. result += line + "\r\n";
  28647. }
  28648. }
  28649. return result;
  28650. };
  28651. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  28652. var root = {
  28653. children: []
  28654. };
  28655. var currentNode = root;
  28656. var lines = shaderString.split("\n");
  28657. for (var index = 0; index < lines.length; index++) {
  28658. var line = lines[index].trim();
  28659. // #ifdef
  28660. var pos = line.indexOf("#ifdef ");
  28661. if (pos !== -1) {
  28662. var define = line.substr(pos + 7);
  28663. var newNode = {
  28664. condition: null,
  28665. ndef: false,
  28666. define: define,
  28667. children: [],
  28668. parent: currentNode
  28669. };
  28670. currentNode.children.push(newNode);
  28671. currentNode = newNode;
  28672. continue;
  28673. }
  28674. // #ifndef
  28675. var pos = line.indexOf("#ifndef ");
  28676. if (pos !== -1) {
  28677. var define = line.substr(pos + 8);
  28678. newNode = {
  28679. condition: null,
  28680. define: define,
  28681. ndef: true,
  28682. children: [],
  28683. parent: currentNode
  28684. };
  28685. currentNode.children.push(newNode);
  28686. currentNode = newNode;
  28687. continue;
  28688. }
  28689. // #if
  28690. var pos = line.indexOf("#if ");
  28691. if (pos !== -1) {
  28692. var define = line.substr(pos + 4).trim();
  28693. var conditionPos = define.indexOf(" ");
  28694. newNode = {
  28695. condition: define.substr(conditionPos + 1),
  28696. define: define.substr(0, conditionPos),
  28697. ndef: false,
  28698. children: [],
  28699. parent: currentNode
  28700. };
  28701. currentNode.children.push(newNode);
  28702. currentNode = newNode;
  28703. continue;
  28704. }
  28705. // #endif
  28706. pos = line.indexOf("#endif");
  28707. if (pos !== -1) {
  28708. currentNode = currentNode.parent;
  28709. continue;
  28710. }
  28711. currentNode.children.push(line);
  28712. }
  28713. // Recombine
  28714. return this._recombineShader(root);
  28715. };
  28716. return Effect;
  28717. }());
  28718. Effect._uniqueIdSeed = 0;
  28719. // Statics
  28720. Effect.ShadersStore = {};
  28721. Effect.IncludesShadersStore = {};
  28722. BABYLON.Effect = Effect;
  28723. })(BABYLON || (BABYLON = {}));
  28724. //# sourceMappingURL=babylon.effect.js.map
  28725. var BABYLON;
  28726. (function (BABYLON) {
  28727. var MaterialHelper = (function () {
  28728. function MaterialHelper() {
  28729. }
  28730. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  28731. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28732. var lightIndex = 0;
  28733. var needNormals = false;
  28734. var needRebuild = false;
  28735. var needShadows = false;
  28736. var lightmapMode = false;
  28737. for (var index = 0; index < scene.lights.length; index++) {
  28738. var light = scene.lights[index];
  28739. if (!light.isEnabled()) {
  28740. continue;
  28741. }
  28742. // Excluded check
  28743. if (light._excludedMeshesIds.length > 0) {
  28744. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  28745. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  28746. if (excludedMesh) {
  28747. light.excludedMeshes.push(excludedMesh);
  28748. }
  28749. }
  28750. light._excludedMeshesIds = [];
  28751. }
  28752. // Included check
  28753. if (light._includedOnlyMeshesIds.length > 0) {
  28754. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  28755. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  28756. if (includedOnlyMesh) {
  28757. light.includedOnlyMeshes.push(includedOnlyMesh);
  28758. }
  28759. }
  28760. light._includedOnlyMeshesIds = [];
  28761. }
  28762. if (!light.canAffectMesh(mesh)) {
  28763. continue;
  28764. }
  28765. needNormals = true;
  28766. if (defines["LIGHT" + lightIndex] === undefined) {
  28767. needRebuild = true;
  28768. }
  28769. defines["LIGHT" + lightIndex] = true;
  28770. var type;
  28771. if (light instanceof BABYLON.SpotLight) {
  28772. type = "SPOTLIGHT" + lightIndex;
  28773. }
  28774. else if (light instanceof BABYLON.HemisphericLight) {
  28775. type = "HEMILIGHT" + lightIndex;
  28776. }
  28777. else if (light instanceof BABYLON.PointLight) {
  28778. type = "POINTLIGHT" + lightIndex;
  28779. }
  28780. else {
  28781. type = "DIRLIGHT" + lightIndex;
  28782. }
  28783. if (defines[type] === undefined) {
  28784. needRebuild = true;
  28785. }
  28786. defines[type] = true;
  28787. // Specular
  28788. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  28789. defines["SPECULARTERM"] = true;
  28790. }
  28791. // Shadows
  28792. if (scene.shadowsEnabled) {
  28793. var shadowGenerator = light.getShadowGenerator();
  28794. if (mesh && mesh.receiveShadows && shadowGenerator) {
  28795. if (defines["SHADOW" + lightIndex] === undefined) {
  28796. needRebuild = true;
  28797. }
  28798. defines["SHADOW" + lightIndex] = true;
  28799. defines["SHADOWS"] = true;
  28800. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  28801. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  28802. needRebuild = true;
  28803. }
  28804. defines["SHADOWVSM" + lightIndex] = true;
  28805. }
  28806. if (shadowGenerator.usePoissonSampling) {
  28807. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  28808. needRebuild = true;
  28809. }
  28810. defines["SHADOWPCF" + lightIndex] = true;
  28811. }
  28812. needShadows = true;
  28813. }
  28814. }
  28815. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  28816. lightmapMode = true;
  28817. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  28818. needRebuild = true;
  28819. }
  28820. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  28821. needRebuild = true;
  28822. }
  28823. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  28824. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  28825. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  28826. }
  28827. }
  28828. lightIndex++;
  28829. if (lightIndex === maxSimultaneousLights)
  28830. break;
  28831. }
  28832. var caps = scene.getEngine().getCaps();
  28833. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  28834. if (defines["SHADOWFULLFLOAT"] === undefined) {
  28835. needRebuild = true;
  28836. }
  28837. defines["SHADOWFULLFLOAT"] = true;
  28838. }
  28839. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  28840. needRebuild = true;
  28841. }
  28842. if (lightmapMode) {
  28843. defines["LIGHTMAPEXCLUDED"] = true;
  28844. }
  28845. if (needRebuild) {
  28846. defines.rebuild();
  28847. }
  28848. return needNormals;
  28849. };
  28850. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  28851. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28852. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28853. if (!defines["LIGHT" + lightIndex]) {
  28854. break;
  28855. }
  28856. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  28857. samplersList.push("shadowSampler" + lightIndex);
  28858. }
  28859. };
  28860. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  28861. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28862. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  28863. if (!defines["LIGHT" + lightIndex]) {
  28864. break;
  28865. }
  28866. if (lightIndex > 0) {
  28867. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  28868. }
  28869. if (defines["SHADOW" + lightIndex]) {
  28870. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  28871. }
  28872. if (defines["SHADOWPCF" + lightIndex]) {
  28873. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  28874. }
  28875. if (defines["SHADOWVSM" + lightIndex]) {
  28876. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  28877. }
  28878. }
  28879. };
  28880. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  28881. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  28882. fallbacks.addCPUSkinningFallback(0, mesh);
  28883. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28884. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28885. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  28886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28888. }
  28889. }
  28890. };
  28891. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  28892. if (defines["INSTANCES"]) {
  28893. attribs.push("world0");
  28894. attribs.push("world1");
  28895. attribs.push("world2");
  28896. attribs.push("world3");
  28897. }
  28898. };
  28899. // Bindings
  28900. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  28901. var shadowGenerator = light.getShadowGenerator();
  28902. if (mesh.receiveShadows && shadowGenerator) {
  28903. if (!light.needCube()) {
  28904. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  28905. }
  28906. else {
  28907. if (!depthValuesAlreadySet) {
  28908. depthValuesAlreadySet = true;
  28909. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  28910. }
  28911. }
  28912. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  28913. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  28914. }
  28915. return depthValuesAlreadySet;
  28916. };
  28917. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  28918. if (light instanceof BABYLON.PointLight) {
  28919. // Point Light
  28920. light.transferToEffect(effect, "vLightData" + lightIndex);
  28921. }
  28922. else if (light instanceof BABYLON.DirectionalLight) {
  28923. // Directional Light
  28924. light.transferToEffect(effect, "vLightData" + lightIndex);
  28925. }
  28926. else if (light instanceof BABYLON.SpotLight) {
  28927. // Spot Light
  28928. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  28929. }
  28930. else if (light instanceof BABYLON.HemisphericLight) {
  28931. // Hemispheric Light
  28932. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  28933. }
  28934. };
  28935. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  28936. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  28937. var lightIndex = 0;
  28938. var depthValuesAlreadySet = false;
  28939. for (var index = 0; index < scene.lights.length; index++) {
  28940. var light = scene.lights[index];
  28941. if (!light.isEnabled()) {
  28942. continue;
  28943. }
  28944. if (!light.canAffectMesh(mesh)) {
  28945. continue;
  28946. }
  28947. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28948. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  28949. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  28950. if (defines["SPECULARTERM"]) {
  28951. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  28952. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  28953. }
  28954. // Shadows
  28955. if (scene.shadowsEnabled) {
  28956. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  28957. }
  28958. lightIndex++;
  28959. if (lightIndex === maxSimultaneousLights)
  28960. break;
  28961. }
  28962. };
  28963. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  28964. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  28965. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  28966. effect.setColor3("vFogColor", scene.fogColor);
  28967. }
  28968. };
  28969. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  28970. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28971. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  28972. if (matrices) {
  28973. effect.setMatrices("mBones", matrices);
  28974. }
  28975. }
  28976. };
  28977. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  28978. if (defines["LOGARITHMICDEPTH"]) {
  28979. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  28980. }
  28981. };
  28982. MaterialHelper.BindClipPlane = function (effect, scene) {
  28983. if (scene.clipPlane) {
  28984. var clipPlane = scene.clipPlane;
  28985. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28986. }
  28987. };
  28988. return MaterialHelper;
  28989. }());
  28990. BABYLON.MaterialHelper = MaterialHelper;
  28991. })(BABYLON || (BABYLON = {}));
  28992. //# sourceMappingURL=babylon.materialHelper.js.map
  28993. var BABYLON;
  28994. (function (BABYLON) {
  28995. var FresnelParameters = (function () {
  28996. function FresnelParameters() {
  28997. this.isEnabled = true;
  28998. this.leftColor = BABYLON.Color3.White();
  28999. this.rightColor = BABYLON.Color3.Black();
  29000. this.bias = 0;
  29001. this.power = 1;
  29002. }
  29003. FresnelParameters.prototype.clone = function () {
  29004. var newFresnelParameters = new FresnelParameters();
  29005. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  29006. return newFresnelParameters;
  29007. };
  29008. FresnelParameters.prototype.serialize = function () {
  29009. var serializationObject = {};
  29010. serializationObject.isEnabled = this.isEnabled;
  29011. serializationObject.leftColor = this.leftColor;
  29012. serializationObject.rightColor = this.rightColor;
  29013. serializationObject.bias = this.bias;
  29014. serializationObject.power = this.power;
  29015. return serializationObject;
  29016. };
  29017. FresnelParameters.Parse = function (parsedFresnelParameters) {
  29018. var fresnelParameters = new FresnelParameters();
  29019. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  29020. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  29021. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  29022. fresnelParameters.bias = parsedFresnelParameters.bias;
  29023. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  29024. return fresnelParameters;
  29025. };
  29026. return FresnelParameters;
  29027. }());
  29028. BABYLON.FresnelParameters = FresnelParameters;
  29029. })(BABYLON || (BABYLON = {}));
  29030. //# sourceMappingURL=babylon.fresnelParameters.js.map
  29031. var BABYLON;
  29032. (function (BABYLON) {
  29033. var MaterialDefines = (function () {
  29034. function MaterialDefines() {
  29035. }
  29036. MaterialDefines.prototype.rebuild = function () {
  29037. if (this._keys) {
  29038. delete this._keys;
  29039. }
  29040. this._keys = Object.keys(this);
  29041. };
  29042. MaterialDefines.prototype.isEqual = function (other) {
  29043. if (this._keys.length !== other._keys.length) {
  29044. return false;
  29045. }
  29046. for (var index = 0; index < this._keys.length; index++) {
  29047. var prop = this._keys[index];
  29048. if (this[prop] !== other[prop]) {
  29049. return false;
  29050. }
  29051. }
  29052. return true;
  29053. };
  29054. MaterialDefines.prototype.cloneTo = function (other) {
  29055. if (this._keys.length !== other._keys.length) {
  29056. other._keys = this._keys.slice(0);
  29057. }
  29058. for (var index = 0; index < this._keys.length; index++) {
  29059. var prop = this._keys[index];
  29060. other[prop] = this[prop];
  29061. }
  29062. };
  29063. MaterialDefines.prototype.reset = function () {
  29064. for (var index = 0; index < this._keys.length; index++) {
  29065. var prop = this._keys[index];
  29066. if (typeof (this[prop]) === "number") {
  29067. this[prop] = 0;
  29068. }
  29069. else {
  29070. this[prop] = false;
  29071. }
  29072. }
  29073. };
  29074. MaterialDefines.prototype.toString = function () {
  29075. var result = "";
  29076. for (var index = 0; index < this._keys.length; index++) {
  29077. var prop = this._keys[index];
  29078. if (typeof (this[prop]) === "number") {
  29079. result += "#define " + prop + " " + this[prop] + "\n";
  29080. }
  29081. else if (this[prop]) {
  29082. result += "#define " + prop + "\n";
  29083. }
  29084. }
  29085. return result;
  29086. };
  29087. return MaterialDefines;
  29088. }());
  29089. BABYLON.MaterialDefines = MaterialDefines;
  29090. var Material = (function () {
  29091. function Material(name, scene, doNotAdd) {
  29092. this.checkReadyOnEveryCall = false;
  29093. this.checkReadyOnlyOnce = false;
  29094. this.state = "";
  29095. this.alpha = 1.0;
  29096. this.backFaceCulling = true;
  29097. this.doNotSerialize = false;
  29098. /**
  29099. * An event triggered when the material is disposed.
  29100. * @type {BABYLON.Observable}
  29101. */
  29102. this.onDisposeObservable = new BABYLON.Observable();
  29103. /**
  29104. * An event triggered when the material is bound.
  29105. * @type {BABYLON.Observable}
  29106. */
  29107. this.onBindObservable = new BABYLON.Observable();
  29108. /**
  29109. * An event triggered when the material is unbound.
  29110. * @type {BABYLON.Observable}
  29111. */
  29112. this.onUnBindObservable = new BABYLON.Observable();
  29113. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29114. this.disableDepthWrite = false;
  29115. this.fogEnabled = true;
  29116. this.pointSize = 1.0;
  29117. this.zOffset = 0;
  29118. this._wasPreviouslyReady = false;
  29119. this._fillMode = Material.TriangleFillMode;
  29120. this.name = name;
  29121. this.id = name;
  29122. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29123. if (this._scene.useRightHandedSystem) {
  29124. this.sideOrientation = Material.ClockWiseSideOrientation;
  29125. }
  29126. else {
  29127. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29128. }
  29129. if (!doNotAdd) {
  29130. this._scene.materials.push(this);
  29131. }
  29132. }
  29133. Object.defineProperty(Material, "TriangleFillMode", {
  29134. get: function () {
  29135. return Material._TriangleFillMode;
  29136. },
  29137. enumerable: true,
  29138. configurable: true
  29139. });
  29140. Object.defineProperty(Material, "WireFrameFillMode", {
  29141. get: function () {
  29142. return Material._WireFrameFillMode;
  29143. },
  29144. enumerable: true,
  29145. configurable: true
  29146. });
  29147. Object.defineProperty(Material, "PointFillMode", {
  29148. get: function () {
  29149. return Material._PointFillMode;
  29150. },
  29151. enumerable: true,
  29152. configurable: true
  29153. });
  29154. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29155. get: function () {
  29156. return Material._ClockWiseSideOrientation;
  29157. },
  29158. enumerable: true,
  29159. configurable: true
  29160. });
  29161. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29162. get: function () {
  29163. return Material._CounterClockWiseSideOrientation;
  29164. },
  29165. enumerable: true,
  29166. configurable: true
  29167. });
  29168. Object.defineProperty(Material.prototype, "onDispose", {
  29169. set: function (callback) {
  29170. if (this._onDisposeObserver) {
  29171. this.onDisposeObservable.remove(this._onDisposeObserver);
  29172. }
  29173. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29174. },
  29175. enumerable: true,
  29176. configurable: true
  29177. });
  29178. Object.defineProperty(Material.prototype, "onBind", {
  29179. set: function (callback) {
  29180. if (this._onBindObserver) {
  29181. this.onBindObservable.remove(this._onBindObserver);
  29182. }
  29183. this._onBindObserver = this.onBindObservable.add(callback);
  29184. },
  29185. enumerable: true,
  29186. configurable: true
  29187. });
  29188. Object.defineProperty(Material.prototype, "wireframe", {
  29189. get: function () {
  29190. return this._fillMode === Material.WireFrameFillMode;
  29191. },
  29192. set: function (value) {
  29193. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29194. },
  29195. enumerable: true,
  29196. configurable: true
  29197. });
  29198. Object.defineProperty(Material.prototype, "pointsCloud", {
  29199. get: function () {
  29200. return this._fillMode === Material.PointFillMode;
  29201. },
  29202. set: function (value) {
  29203. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29204. },
  29205. enumerable: true,
  29206. configurable: true
  29207. });
  29208. Object.defineProperty(Material.prototype, "fillMode", {
  29209. get: function () {
  29210. return this._fillMode;
  29211. },
  29212. set: function (value) {
  29213. this._fillMode = value;
  29214. },
  29215. enumerable: true,
  29216. configurable: true
  29217. });
  29218. /**
  29219. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29220. * subclasses should override adding information pertainent to themselves
  29221. */
  29222. Material.prototype.toString = function (fullDetails) {
  29223. var ret = "Name: " + this.name;
  29224. if (fullDetails) {
  29225. }
  29226. return ret;
  29227. };
  29228. Material.prototype.getClassName = function () {
  29229. return "Material";
  29230. };
  29231. Object.defineProperty(Material.prototype, "isFrozen", {
  29232. get: function () {
  29233. return this.checkReadyOnlyOnce;
  29234. },
  29235. enumerable: true,
  29236. configurable: true
  29237. });
  29238. Material.prototype.freeze = function () {
  29239. this.checkReadyOnlyOnce = true;
  29240. };
  29241. Material.prototype.unfreeze = function () {
  29242. this.checkReadyOnlyOnce = false;
  29243. };
  29244. Material.prototype.isReady = function (mesh, useInstances) {
  29245. return true;
  29246. };
  29247. Material.prototype.getEffect = function () {
  29248. return this._effect;
  29249. };
  29250. Material.prototype.getScene = function () {
  29251. return this._scene;
  29252. };
  29253. Material.prototype.needAlphaBlending = function () {
  29254. return (this.alpha < 1.0);
  29255. };
  29256. Material.prototype.needAlphaTesting = function () {
  29257. return false;
  29258. };
  29259. Material.prototype.getAlphaTestTexture = function () {
  29260. return null;
  29261. };
  29262. Material.prototype.markDirty = function () {
  29263. this._wasPreviouslyReady = false;
  29264. };
  29265. Material.prototype._preBind = function () {
  29266. var engine = this._scene.getEngine();
  29267. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29268. engine.enableEffect(this._effect);
  29269. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29270. };
  29271. Material.prototype.bind = function (world, mesh) {
  29272. this._scene._cachedMaterial = this;
  29273. this.onBindObservable.notifyObservers(mesh);
  29274. if (this.disableDepthWrite) {
  29275. var engine = this._scene.getEngine();
  29276. this._cachedDepthWriteState = engine.getDepthWrite();
  29277. engine.setDepthWrite(false);
  29278. }
  29279. };
  29280. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29281. };
  29282. Material.prototype.unbind = function () {
  29283. this.onUnBindObservable.notifyObservers(this);
  29284. if (this.disableDepthWrite) {
  29285. var engine = this._scene.getEngine();
  29286. engine.setDepthWrite(this._cachedDepthWriteState);
  29287. }
  29288. };
  29289. Material.prototype.clone = function (name) {
  29290. return null;
  29291. };
  29292. Material.prototype.getBindedMeshes = function () {
  29293. var result = new Array();
  29294. for (var index = 0; index < this._scene.meshes.length; index++) {
  29295. var mesh = this._scene.meshes[index];
  29296. if (mesh.material === this) {
  29297. result.push(mesh);
  29298. }
  29299. }
  29300. return result;
  29301. };
  29302. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29303. // Animations
  29304. this.getScene().stopAnimation(this);
  29305. // Remove from scene
  29306. var index = this._scene.materials.indexOf(this);
  29307. if (index >= 0) {
  29308. this._scene.materials.splice(index, 1);
  29309. }
  29310. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29311. if (forceDisposeEffect && this._effect) {
  29312. this._scene.getEngine()._releaseEffect(this._effect);
  29313. this._effect = null;
  29314. }
  29315. // Remove from meshes
  29316. for (index = 0; index < this._scene.meshes.length; index++) {
  29317. var mesh = this._scene.meshes[index];
  29318. if (mesh.material === this) {
  29319. mesh.material = null;
  29320. }
  29321. }
  29322. // Callback
  29323. this.onDisposeObservable.notifyObservers(this);
  29324. this.onDisposeObservable.clear();
  29325. this.onBindObservable.clear();
  29326. this.onUnBindObservable.clear();
  29327. };
  29328. Material.prototype.serialize = function () {
  29329. return BABYLON.SerializationHelper.Serialize(this);
  29330. };
  29331. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29332. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29333. multiMaterial.id = parsedMultiMaterial.id;
  29334. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29335. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29336. var subMatId = parsedMultiMaterial.materials[matIndex];
  29337. if (subMatId) {
  29338. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29339. }
  29340. else {
  29341. multiMaterial.subMaterials.push(null);
  29342. }
  29343. }
  29344. return multiMaterial;
  29345. };
  29346. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29347. if (!parsedMaterial.customType) {
  29348. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29349. }
  29350. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29351. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29352. ;
  29353. };
  29354. return Material;
  29355. }());
  29356. Material._TriangleFillMode = 0;
  29357. Material._WireFrameFillMode = 1;
  29358. Material._PointFillMode = 2;
  29359. Material._ClockWiseSideOrientation = 0;
  29360. Material._CounterClockWiseSideOrientation = 1;
  29361. __decorate([
  29362. BABYLON.serialize()
  29363. ], Material.prototype, "id", void 0);
  29364. __decorate([
  29365. BABYLON.serialize()
  29366. ], Material.prototype, "name", void 0);
  29367. __decorate([
  29368. BABYLON.serialize()
  29369. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29370. __decorate([
  29371. BABYLON.serialize()
  29372. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29373. __decorate([
  29374. BABYLON.serialize()
  29375. ], Material.prototype, "state", void 0);
  29376. __decorate([
  29377. BABYLON.serialize()
  29378. ], Material.prototype, "alpha", void 0);
  29379. __decorate([
  29380. BABYLON.serialize()
  29381. ], Material.prototype, "backFaceCulling", void 0);
  29382. __decorate([
  29383. BABYLON.serialize()
  29384. ], Material.prototype, "sideOrientation", void 0);
  29385. __decorate([
  29386. BABYLON.serialize()
  29387. ], Material.prototype, "alphaMode", void 0);
  29388. __decorate([
  29389. BABYLON.serialize()
  29390. ], Material.prototype, "disableDepthWrite", void 0);
  29391. __decorate([
  29392. BABYLON.serialize()
  29393. ], Material.prototype, "fogEnabled", void 0);
  29394. __decorate([
  29395. BABYLON.serialize()
  29396. ], Material.prototype, "pointSize", void 0);
  29397. __decorate([
  29398. BABYLON.serialize()
  29399. ], Material.prototype, "zOffset", void 0);
  29400. __decorate([
  29401. BABYLON.serialize()
  29402. ], Material.prototype, "wireframe", null);
  29403. __decorate([
  29404. BABYLON.serialize()
  29405. ], Material.prototype, "pointsCloud", null);
  29406. __decorate([
  29407. BABYLON.serialize()
  29408. ], Material.prototype, "fillMode", null);
  29409. BABYLON.Material = Material;
  29410. })(BABYLON || (BABYLON = {}));
  29411. //# sourceMappingURL=babylon.material.js.map
  29412. var BABYLON;
  29413. (function (BABYLON) {
  29414. var StandardMaterialDefines = (function (_super) {
  29415. __extends(StandardMaterialDefines, _super);
  29416. function StandardMaterialDefines() {
  29417. var _this = _super.call(this) || this;
  29418. _this.DIFFUSE = false;
  29419. _this.AMBIENT = false;
  29420. _this.OPACITY = false;
  29421. _this.OPACITYRGB = false;
  29422. _this.REFLECTION = false;
  29423. _this.EMISSIVE = false;
  29424. _this.SPECULAR = false;
  29425. _this.BUMP = false;
  29426. _this.PARALLAX = false;
  29427. _this.PARALLAXOCCLUSION = false;
  29428. _this.SPECULAROVERALPHA = false;
  29429. _this.CLIPPLANE = false;
  29430. _this.ALPHATEST = false;
  29431. _this.ALPHAFROMDIFFUSE = false;
  29432. _this.POINTSIZE = false;
  29433. _this.FOG = false;
  29434. _this.SPECULARTERM = false;
  29435. _this.DIFFUSEFRESNEL = false;
  29436. _this.OPACITYFRESNEL = false;
  29437. _this.REFLECTIONFRESNEL = false;
  29438. _this.REFRACTIONFRESNEL = false;
  29439. _this.EMISSIVEFRESNEL = false;
  29440. _this.FRESNEL = false;
  29441. _this.NORMAL = false;
  29442. _this.UV1 = false;
  29443. _this.UV2 = false;
  29444. _this.VERTEXCOLOR = false;
  29445. _this.VERTEXALPHA = false;
  29446. _this.NUM_BONE_INFLUENCERS = 0;
  29447. _this.BonesPerMesh = 0;
  29448. _this.INSTANCES = false;
  29449. _this.GLOSSINESS = false;
  29450. _this.ROUGHNESS = false;
  29451. _this.EMISSIVEASILLUMINATION = false;
  29452. _this.LINKEMISSIVEWITHDIFFUSE = false;
  29453. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  29454. _this.LIGHTMAP = false;
  29455. _this.USELIGHTMAPASSHADOWMAP = false;
  29456. _this.REFLECTIONMAP_3D = false;
  29457. _this.REFLECTIONMAP_SPHERICAL = false;
  29458. _this.REFLECTIONMAP_PLANAR = false;
  29459. _this.REFLECTIONMAP_CUBIC = false;
  29460. _this.REFLECTIONMAP_PROJECTION = false;
  29461. _this.REFLECTIONMAP_SKYBOX = false;
  29462. _this.REFLECTIONMAP_EXPLICIT = false;
  29463. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  29464. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  29465. _this.INVERTCUBICMAP = false;
  29466. _this.LOGARITHMICDEPTH = false;
  29467. _this.REFRACTION = false;
  29468. _this.REFRACTIONMAP_3D = false;
  29469. _this.REFLECTIONOVERALPHA = false;
  29470. _this.INVERTNORMALMAPX = false;
  29471. _this.INVERTNORMALMAPY = false;
  29472. _this.SHADOWFULLFLOAT = false;
  29473. _this.CAMERACOLORGRADING = false;
  29474. _this.CAMERACOLORCURVES = false;
  29475. _this.rebuild();
  29476. return _this;
  29477. }
  29478. return StandardMaterialDefines;
  29479. }(BABYLON.MaterialDefines));
  29480. var StandardMaterial = (function (_super) {
  29481. __extends(StandardMaterial, _super);
  29482. function StandardMaterial(name, scene) {
  29483. var _this = _super.call(this, name, scene) || this;
  29484. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  29485. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  29486. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  29487. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  29488. _this.specularPower = 64;
  29489. _this.useAlphaFromDiffuseTexture = false;
  29490. _this.useEmissiveAsIllumination = false;
  29491. _this.linkEmissiveWithDiffuse = false;
  29492. _this.useReflectionFresnelFromSpecular = false;
  29493. _this.useSpecularOverAlpha = false;
  29494. _this.useReflectionOverAlpha = false;
  29495. _this.disableLighting = false;
  29496. _this.useParallax = false;
  29497. _this.useParallaxOcclusion = false;
  29498. _this.parallaxScaleBias = 0.05;
  29499. _this.roughness = 0;
  29500. _this.indexOfRefraction = 0.98;
  29501. _this.invertRefractionY = true;
  29502. _this.useLightmapAsShadowmap = false;
  29503. _this.useGlossinessFromSpecularMapAlpha = false;
  29504. _this.maxSimultaneousLights = 4;
  29505. /**
  29506. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  29507. */
  29508. _this.invertNormalMapX = false;
  29509. /**
  29510. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  29511. */
  29512. _this.invertNormalMapY = false;
  29513. /**
  29514. * Color Grading 2D Lookup Texture.
  29515. * This allows special effects like sepia, black and white to sixties rendering style.
  29516. */
  29517. _this.cameraColorGradingTexture = null;
  29518. /**
  29519. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  29520. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  29521. * 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;
  29522. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  29523. */
  29524. _this.cameraColorCurves = null;
  29525. _this._renderTargets = new BABYLON.SmartArray(16);
  29526. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  29527. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  29528. _this._defines = new StandardMaterialDefines();
  29529. _this._cachedDefines = new StandardMaterialDefines();
  29530. _this._cachedDefines.BonesPerMesh = -1;
  29531. _this.getRenderTargetTextures = function () {
  29532. _this._renderTargets.reset();
  29533. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  29534. _this._renderTargets.push(_this.reflectionTexture);
  29535. }
  29536. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  29537. _this._renderTargets.push(_this.refractionTexture);
  29538. }
  29539. return _this._renderTargets;
  29540. };
  29541. return _this;
  29542. }
  29543. StandardMaterial.prototype.getClassName = function () {
  29544. return "StandardMaterial";
  29545. };
  29546. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  29547. get: function () {
  29548. return this._useLogarithmicDepth;
  29549. },
  29550. set: function (value) {
  29551. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. StandardMaterial.prototype.needAlphaBlending = function () {
  29557. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  29558. };
  29559. StandardMaterial.prototype.needAlphaTesting = function () {
  29560. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  29561. };
  29562. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  29563. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  29564. };
  29565. StandardMaterial.prototype.getAlphaTestTexture = function () {
  29566. return this.diffuseTexture;
  29567. };
  29568. // Methods
  29569. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  29570. if (!mesh) {
  29571. return true;
  29572. }
  29573. if (this._defines.INSTANCES !== useInstances) {
  29574. return false;
  29575. }
  29576. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  29577. return true;
  29578. }
  29579. return false;
  29580. };
  29581. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  29582. if (this.isFrozen) {
  29583. if (this._wasPreviouslyReady) {
  29584. return true;
  29585. }
  29586. }
  29587. var scene = this.getScene();
  29588. var engine = scene.getEngine();
  29589. var needUVs = false;
  29590. var needNormals = false;
  29591. this._defines.reset();
  29592. // Lights
  29593. if (scene.lightsEnabled && !this.disableLighting) {
  29594. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  29595. }
  29596. if (!this.checkReadyOnEveryCall) {
  29597. if (this._renderId === scene.getRenderId()) {
  29598. if (this._checkCache(scene, mesh, useInstances)) {
  29599. return true;
  29600. }
  29601. }
  29602. }
  29603. // Textures
  29604. if (scene.texturesEnabled) {
  29605. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29606. if (!this.diffuseTexture.isReady()) {
  29607. return false;
  29608. }
  29609. else {
  29610. needUVs = true;
  29611. this._defines.DIFFUSE = true;
  29612. }
  29613. }
  29614. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29615. if (!this.ambientTexture.isReady()) {
  29616. return false;
  29617. }
  29618. else {
  29619. needUVs = true;
  29620. this._defines.AMBIENT = true;
  29621. }
  29622. }
  29623. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  29624. if (!this.opacityTexture.isReady()) {
  29625. return false;
  29626. }
  29627. else {
  29628. needUVs = true;
  29629. this._defines.OPACITY = true;
  29630. if (this.opacityTexture.getAlphaFromRGB) {
  29631. this._defines.OPACITYRGB = true;
  29632. }
  29633. }
  29634. }
  29635. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  29636. if (!this.reflectionTexture.isReady()) {
  29637. return false;
  29638. }
  29639. else {
  29640. needNormals = true;
  29641. this._defines.REFLECTION = true;
  29642. if (this.roughness > 0) {
  29643. this._defines.ROUGHNESS = true;
  29644. }
  29645. if (this.useReflectionOverAlpha) {
  29646. this._defines.REFLECTIONOVERALPHA = true;
  29647. }
  29648. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  29649. this._defines.INVERTCUBICMAP = true;
  29650. }
  29651. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  29652. switch (this.reflectionTexture.coordinatesMode) {
  29653. case BABYLON.Texture.CUBIC_MODE:
  29654. case BABYLON.Texture.INVCUBIC_MODE:
  29655. this._defines.REFLECTIONMAP_CUBIC = true;
  29656. break;
  29657. case BABYLON.Texture.EXPLICIT_MODE:
  29658. this._defines.REFLECTIONMAP_EXPLICIT = true;
  29659. break;
  29660. case BABYLON.Texture.PLANAR_MODE:
  29661. this._defines.REFLECTIONMAP_PLANAR = true;
  29662. break;
  29663. case BABYLON.Texture.PROJECTION_MODE:
  29664. this._defines.REFLECTIONMAP_PROJECTION = true;
  29665. break;
  29666. case BABYLON.Texture.SKYBOX_MODE:
  29667. this._defines.REFLECTIONMAP_SKYBOX = true;
  29668. break;
  29669. case BABYLON.Texture.SPHERICAL_MODE:
  29670. this._defines.REFLECTIONMAP_SPHERICAL = true;
  29671. break;
  29672. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  29673. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  29674. break;
  29675. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  29676. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  29677. break;
  29678. }
  29679. }
  29680. }
  29681. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  29682. if (!this.emissiveTexture.isReady()) {
  29683. return false;
  29684. }
  29685. else {
  29686. needUVs = true;
  29687. this._defines.EMISSIVE = true;
  29688. }
  29689. }
  29690. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  29691. if (!this.lightmapTexture.isReady()) {
  29692. return false;
  29693. }
  29694. else {
  29695. needUVs = true;
  29696. this._defines.LIGHTMAP = true;
  29697. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  29698. }
  29699. }
  29700. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  29701. if (!this.specularTexture.isReady()) {
  29702. return false;
  29703. }
  29704. else {
  29705. needUVs = true;
  29706. this._defines.SPECULAR = true;
  29707. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  29708. }
  29709. }
  29710. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  29711. if (!this.bumpTexture.isReady()) {
  29712. return false;
  29713. }
  29714. else {
  29715. needUVs = true;
  29716. this._defines.BUMP = true;
  29717. if (this.useParallax) {
  29718. this._defines.PARALLAX = true;
  29719. if (this.useParallaxOcclusion) {
  29720. this._defines.PARALLAXOCCLUSION = true;
  29721. }
  29722. }
  29723. if (this.invertNormalMapX) {
  29724. this._defines.INVERTNORMALMAPX = true;
  29725. }
  29726. if (this.invertNormalMapY) {
  29727. this._defines.INVERTNORMALMAPY = true;
  29728. }
  29729. if (scene._mirroredCameraPosition) {
  29730. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29731. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29732. }
  29733. }
  29734. }
  29735. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  29736. if (!this.refractionTexture.isReady()) {
  29737. return false;
  29738. }
  29739. else {
  29740. needUVs = true;
  29741. this._defines.REFRACTION = true;
  29742. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  29743. }
  29744. }
  29745. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  29746. if (!this.cameraColorGradingTexture.isReady()) {
  29747. return false;
  29748. }
  29749. else {
  29750. this._defines.CAMERACOLORGRADING = true;
  29751. }
  29752. }
  29753. }
  29754. // Effect
  29755. if (scene.clipPlane) {
  29756. this._defines.CLIPPLANE = true;
  29757. }
  29758. if (engine.getAlphaTesting()) {
  29759. this._defines.ALPHATEST = true;
  29760. }
  29761. if (this._shouldUseAlphaFromDiffuseTexture()) {
  29762. this._defines.ALPHAFROMDIFFUSE = true;
  29763. }
  29764. if (this.useEmissiveAsIllumination) {
  29765. this._defines.EMISSIVEASILLUMINATION = true;
  29766. }
  29767. if (this.linkEmissiveWithDiffuse) {
  29768. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  29769. }
  29770. if (this.useLogarithmicDepth) {
  29771. this._defines.LOGARITHMICDEPTH = true;
  29772. }
  29773. if (this.cameraColorCurves) {
  29774. this._defines.CAMERACOLORCURVES = true;
  29775. }
  29776. // Point size
  29777. if (this.pointsCloud || scene.forcePointsCloud) {
  29778. this._defines.POINTSIZE = true;
  29779. }
  29780. // Fog
  29781. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29782. this._defines.FOG = true;
  29783. }
  29784. if (StandardMaterial.FresnelEnabled) {
  29785. // Fresnel
  29786. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  29787. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29788. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  29789. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  29790. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29791. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29792. this._defines.DIFFUSEFRESNEL = true;
  29793. }
  29794. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29795. this._defines.OPACITYFRESNEL = true;
  29796. }
  29797. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29798. this._defines.REFLECTIONFRESNEL = true;
  29799. if (this.useReflectionFresnelFromSpecular) {
  29800. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  29801. }
  29802. }
  29803. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29804. this._defines.REFRACTIONFRESNEL = true;
  29805. }
  29806. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29807. this._defines.EMISSIVEFRESNEL = true;
  29808. }
  29809. needNormals = true;
  29810. this._defines.FRESNEL = true;
  29811. }
  29812. }
  29813. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29814. this._defines.SPECULAROVERALPHA = true;
  29815. }
  29816. // Attribs
  29817. if (mesh) {
  29818. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29819. this._defines.NORMAL = true;
  29820. }
  29821. if (needUVs) {
  29822. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29823. this._defines.UV1 = true;
  29824. }
  29825. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29826. this._defines.UV2 = true;
  29827. }
  29828. }
  29829. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29830. this._defines.VERTEXCOLOR = true;
  29831. if (mesh.hasVertexAlpha) {
  29832. this._defines.VERTEXALPHA = true;
  29833. }
  29834. }
  29835. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29836. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29837. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29838. }
  29839. // Instances
  29840. if (useInstances) {
  29841. this._defines.INSTANCES = true;
  29842. }
  29843. }
  29844. // Get correct effect
  29845. if (!this._defines.isEqual(this._cachedDefines)) {
  29846. this._defines.cloneTo(this._cachedDefines);
  29847. scene.resetCachedMaterial();
  29848. // Fallbacks
  29849. var fallbacks = new BABYLON.EffectFallbacks();
  29850. if (this._defines.REFLECTION) {
  29851. fallbacks.addFallback(0, "REFLECTION");
  29852. }
  29853. if (this._defines.SPECULAR) {
  29854. fallbacks.addFallback(0, "SPECULAR");
  29855. }
  29856. if (this._defines.BUMP) {
  29857. fallbacks.addFallback(0, "BUMP");
  29858. }
  29859. if (this._defines.PARALLAX) {
  29860. fallbacks.addFallback(1, "PARALLAX");
  29861. }
  29862. if (this._defines.PARALLAXOCCLUSION) {
  29863. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29864. }
  29865. if (this._defines.SPECULAROVERALPHA) {
  29866. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29867. }
  29868. if (this._defines.FOG) {
  29869. fallbacks.addFallback(1, "FOG");
  29870. }
  29871. if (this._defines.POINTSIZE) {
  29872. fallbacks.addFallback(0, "POINTSIZE");
  29873. }
  29874. if (this._defines.LOGARITHMICDEPTH) {
  29875. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29876. }
  29877. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29878. if (this._defines.SPECULARTERM) {
  29879. fallbacks.addFallback(0, "SPECULARTERM");
  29880. }
  29881. if (this._defines.DIFFUSEFRESNEL) {
  29882. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  29883. }
  29884. if (this._defines.OPACITYFRESNEL) {
  29885. fallbacks.addFallback(2, "OPACITYFRESNEL");
  29886. }
  29887. if (this._defines.REFLECTIONFRESNEL) {
  29888. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  29889. }
  29890. if (this._defines.EMISSIVEFRESNEL) {
  29891. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  29892. }
  29893. if (this._defines.FRESNEL) {
  29894. fallbacks.addFallback(4, "FRESNEL");
  29895. }
  29896. //Attributes
  29897. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29898. if (this._defines.NORMAL) {
  29899. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29900. }
  29901. if (this._defines.UV1) {
  29902. attribs.push(BABYLON.VertexBuffer.UVKind);
  29903. }
  29904. if (this._defines.UV2) {
  29905. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29906. }
  29907. if (this._defines.VERTEXCOLOR) {
  29908. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29909. }
  29910. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29911. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29912. var shaderName = "default";
  29913. var join = this._defines.toString();
  29914. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  29915. "vFogInfos", "vFogColor", "pointSize",
  29916. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29917. "mBones",
  29918. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29919. "depthValues",
  29920. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  29921. "logarithmicDepthConstant"
  29922. ];
  29923. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29924. if (this._defines.CAMERACOLORCURVES) {
  29925. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29926. }
  29927. if (this._defines.CAMERACOLORGRADING) {
  29928. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29929. }
  29930. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  29931. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  29932. }
  29933. if (!this._effect.isReady()) {
  29934. return false;
  29935. }
  29936. this._renderId = scene.getRenderId();
  29937. this._wasPreviouslyReady = true;
  29938. if (mesh) {
  29939. if (!mesh._materialDefines) {
  29940. mesh._materialDefines = new StandardMaterialDefines();
  29941. }
  29942. this._defines.cloneTo(mesh._materialDefines);
  29943. }
  29944. return true;
  29945. };
  29946. StandardMaterial.prototype.unbind = function () {
  29947. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29948. this._effect.setTexture("reflection2DSampler", null);
  29949. }
  29950. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29951. this._effect.setTexture("refraction2DSampler", null);
  29952. }
  29953. _super.prototype.unbind.call(this);
  29954. };
  29955. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29956. this._effect.setMatrix("world", world);
  29957. };
  29958. StandardMaterial.prototype.bind = function (world, mesh) {
  29959. var scene = this.getScene();
  29960. // Matrices
  29961. this.bindOnlyWorldMatrix(world);
  29962. // Bones
  29963. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29964. if (scene.getCachedMaterial() !== this) {
  29965. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29966. if (StandardMaterial.FresnelEnabled) {
  29967. // Fresnel
  29968. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  29969. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  29970. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  29971. }
  29972. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29973. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29974. }
  29975. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  29976. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  29977. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  29978. }
  29979. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  29980. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  29981. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  29982. }
  29983. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29984. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29985. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29986. }
  29987. }
  29988. // Textures
  29989. if (scene.texturesEnabled) {
  29990. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  29991. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  29992. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  29993. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  29994. }
  29995. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  29996. this._effect.setTexture("ambientSampler", this.ambientTexture);
  29997. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  29998. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29999. }
  30000. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30001. this._effect.setTexture("opacitySampler", this.opacityTexture);
  30002. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  30003. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  30004. }
  30005. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30006. if (this.reflectionTexture.isCube) {
  30007. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  30008. }
  30009. else {
  30010. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  30011. }
  30012. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  30013. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  30014. }
  30015. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30016. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  30017. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  30018. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  30019. }
  30020. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30021. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  30022. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  30023. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  30024. }
  30025. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30026. this._effect.setTexture("specularSampler", this.specularTexture);
  30027. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  30028. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  30029. }
  30030. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30031. this._effect.setTexture("bumpSampler", this.bumpTexture);
  30032. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  30033. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  30034. }
  30035. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30036. var depth = 1.0;
  30037. if (this.refractionTexture.isCube) {
  30038. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  30039. }
  30040. else {
  30041. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  30042. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  30043. if (this.refractionTexture.depth) {
  30044. depth = this.refractionTexture.depth;
  30045. }
  30046. }
  30047. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30048. }
  30049. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30050. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  30051. }
  30052. }
  30053. // Clip plane
  30054. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  30055. // Point size
  30056. if (this.pointsCloud) {
  30057. this._effect.setFloat("pointSize", this.pointSize);
  30058. }
  30059. // Colors
  30060. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30061. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30062. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30063. if (this._defines.SPECULARTERM) {
  30064. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  30065. }
  30066. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  30067. }
  30068. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  30069. // Diffuse
  30070. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30071. // Lights
  30072. if (scene.lightsEnabled && !this.disableLighting) {
  30073. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  30074. }
  30075. // View
  30076. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  30077. this._effect.setMatrix("view", scene.getViewMatrix());
  30078. }
  30079. // Fog
  30080. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  30081. // Log. depth
  30082. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  30083. // Color Curves
  30084. if (this.cameraColorCurves) {
  30085. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  30086. }
  30087. }
  30088. _super.prototype.bind.call(this, world, mesh);
  30089. };
  30090. StandardMaterial.prototype.getAnimatables = function () {
  30091. var results = [];
  30092. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  30093. results.push(this.diffuseTexture);
  30094. }
  30095. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  30096. results.push(this.ambientTexture);
  30097. }
  30098. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  30099. results.push(this.opacityTexture);
  30100. }
  30101. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  30102. results.push(this.reflectionTexture);
  30103. }
  30104. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  30105. results.push(this.emissiveTexture);
  30106. }
  30107. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  30108. results.push(this.specularTexture);
  30109. }
  30110. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  30111. results.push(this.bumpTexture);
  30112. }
  30113. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  30114. results.push(this.lightmapTexture);
  30115. }
  30116. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  30117. results.push(this.refractionTexture);
  30118. }
  30119. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  30120. results.push(this.cameraColorGradingTexture);
  30121. }
  30122. return results;
  30123. };
  30124. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30125. if (forceDisposeTextures) {
  30126. if (this.diffuseTexture) {
  30127. this.diffuseTexture.dispose();
  30128. }
  30129. if (this.ambientTexture) {
  30130. this.ambientTexture.dispose();
  30131. }
  30132. if (this.opacityTexture) {
  30133. this.opacityTexture.dispose();
  30134. }
  30135. if (this.reflectionTexture) {
  30136. this.reflectionTexture.dispose();
  30137. }
  30138. if (this.emissiveTexture) {
  30139. this.emissiveTexture.dispose();
  30140. }
  30141. if (this.specularTexture) {
  30142. this.specularTexture.dispose();
  30143. }
  30144. if (this.bumpTexture) {
  30145. this.bumpTexture.dispose();
  30146. }
  30147. if (this.lightmapTexture) {
  30148. this.lightmapTexture.dispose();
  30149. }
  30150. if (this.refractionTexture) {
  30151. this.refractionTexture.dispose();
  30152. }
  30153. if (this.cameraColorGradingTexture) {
  30154. this.cameraColorGradingTexture.dispose();
  30155. }
  30156. }
  30157. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30158. };
  30159. StandardMaterial.prototype.clone = function (name) {
  30160. var _this = this;
  30161. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30162. };
  30163. StandardMaterial.prototype.serialize = function () {
  30164. return BABYLON.SerializationHelper.Serialize(this);
  30165. };
  30166. // Statics
  30167. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30168. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30169. };
  30170. return StandardMaterial;
  30171. }(BABYLON.Material));
  30172. // Flags used to enable or disable a type of texture for all Standard Materials
  30173. StandardMaterial.DiffuseTextureEnabled = true;
  30174. StandardMaterial.AmbientTextureEnabled = true;
  30175. StandardMaterial.OpacityTextureEnabled = true;
  30176. StandardMaterial.ReflectionTextureEnabled = true;
  30177. StandardMaterial.EmissiveTextureEnabled = true;
  30178. StandardMaterial.SpecularTextureEnabled = true;
  30179. StandardMaterial.BumpTextureEnabled = true;
  30180. StandardMaterial.FresnelEnabled = true;
  30181. StandardMaterial.LightmapTextureEnabled = true;
  30182. StandardMaterial.RefractionTextureEnabled = true;
  30183. StandardMaterial.ColorGradingTextureEnabled = true;
  30184. __decorate([
  30185. BABYLON.serializeAsTexture()
  30186. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30187. __decorate([
  30188. BABYLON.serializeAsTexture()
  30189. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30190. __decorate([
  30191. BABYLON.serializeAsTexture()
  30192. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30193. __decorate([
  30194. BABYLON.serializeAsTexture()
  30195. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30196. __decorate([
  30197. BABYLON.serializeAsTexture()
  30198. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30199. __decorate([
  30200. BABYLON.serializeAsTexture()
  30201. ], StandardMaterial.prototype, "specularTexture", void 0);
  30202. __decorate([
  30203. BABYLON.serializeAsTexture()
  30204. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30205. __decorate([
  30206. BABYLON.serializeAsTexture()
  30207. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30208. __decorate([
  30209. BABYLON.serializeAsTexture()
  30210. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30211. __decorate([
  30212. BABYLON.serializeAsColor3("ambient")
  30213. ], StandardMaterial.prototype, "ambientColor", void 0);
  30214. __decorate([
  30215. BABYLON.serializeAsColor3("diffuse")
  30216. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30217. __decorate([
  30218. BABYLON.serializeAsColor3("specular")
  30219. ], StandardMaterial.prototype, "specularColor", void 0);
  30220. __decorate([
  30221. BABYLON.serializeAsColor3("emissive")
  30222. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30223. __decorate([
  30224. BABYLON.serialize()
  30225. ], StandardMaterial.prototype, "specularPower", void 0);
  30226. __decorate([
  30227. BABYLON.serialize()
  30228. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30229. __decorate([
  30230. BABYLON.serialize()
  30231. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30232. __decorate([
  30233. BABYLON.serialize()
  30234. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30235. __decorate([
  30236. BABYLON.serialize()
  30237. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30238. __decorate([
  30239. BABYLON.serialize()
  30240. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30241. __decorate([
  30242. BABYLON.serialize()
  30243. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30244. __decorate([
  30245. BABYLON.serialize()
  30246. ], StandardMaterial.prototype, "disableLighting", void 0);
  30247. __decorate([
  30248. BABYLON.serialize()
  30249. ], StandardMaterial.prototype, "useParallax", void 0);
  30250. __decorate([
  30251. BABYLON.serialize()
  30252. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30253. __decorate([
  30254. BABYLON.serialize()
  30255. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30256. __decorate([
  30257. BABYLON.serialize()
  30258. ], StandardMaterial.prototype, "roughness", void 0);
  30259. __decorate([
  30260. BABYLON.serialize()
  30261. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30262. __decorate([
  30263. BABYLON.serialize()
  30264. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30265. __decorate([
  30266. BABYLON.serialize()
  30267. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30268. __decorate([
  30269. BABYLON.serializeAsFresnelParameters()
  30270. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30271. __decorate([
  30272. BABYLON.serializeAsFresnelParameters()
  30273. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30274. __decorate([
  30275. BABYLON.serializeAsFresnelParameters()
  30276. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30277. __decorate([
  30278. BABYLON.serializeAsFresnelParameters()
  30279. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30280. __decorate([
  30281. BABYLON.serializeAsFresnelParameters()
  30282. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30283. __decorate([
  30284. BABYLON.serialize()
  30285. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30286. __decorate([
  30287. BABYLON.serialize()
  30288. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30289. __decorate([
  30290. BABYLON.serialize()
  30291. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30292. __decorate([
  30293. BABYLON.serialize()
  30294. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30295. __decorate([
  30296. BABYLON.serializeAsTexture()
  30297. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30298. __decorate([
  30299. BABYLON.serializeAsColorCurves()
  30300. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30301. __decorate([
  30302. BABYLON.serialize()
  30303. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30304. BABYLON.StandardMaterial = StandardMaterial;
  30305. })(BABYLON || (BABYLON = {}));
  30306. //# sourceMappingURL=babylon.standardMaterial.js.map
  30307. var BABYLON;
  30308. (function (BABYLON) {
  30309. var MultiMaterial = (function (_super) {
  30310. __extends(MultiMaterial, _super);
  30311. function MultiMaterial(name, scene) {
  30312. var _this = _super.call(this, name, scene, true) || this;
  30313. _this.subMaterials = new Array();
  30314. scene.multiMaterials.push(_this);
  30315. return _this;
  30316. }
  30317. // Properties
  30318. MultiMaterial.prototype.getSubMaterial = function (index) {
  30319. if (index < 0 || index >= this.subMaterials.length) {
  30320. return this.getScene().defaultMaterial;
  30321. }
  30322. return this.subMaterials[index];
  30323. };
  30324. // Methods
  30325. MultiMaterial.prototype.getClassName = function () {
  30326. return "MultiMaterial";
  30327. };
  30328. MultiMaterial.prototype.isReady = function (mesh) {
  30329. for (var index = 0; index < this.subMaterials.length; index++) {
  30330. var subMaterial = this.subMaterials[index];
  30331. if (subMaterial) {
  30332. if (!this.subMaterials[index].isReady(mesh)) {
  30333. return false;
  30334. }
  30335. }
  30336. }
  30337. return true;
  30338. };
  30339. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30340. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30341. for (var index = 0; index < this.subMaterials.length; index++) {
  30342. var subMaterial = null;
  30343. if (cloneChildren) {
  30344. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30345. }
  30346. else {
  30347. subMaterial = this.subMaterials[index];
  30348. }
  30349. newMultiMaterial.subMaterials.push(subMaterial);
  30350. }
  30351. return newMultiMaterial;
  30352. };
  30353. MultiMaterial.prototype.serialize = function () {
  30354. var serializationObject = {};
  30355. serializationObject.name = this.name;
  30356. serializationObject.id = this.id;
  30357. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30358. serializationObject.materials = [];
  30359. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30360. var subMat = this.subMaterials[matIndex];
  30361. if (subMat) {
  30362. serializationObject.materials.push(subMat.id);
  30363. }
  30364. else {
  30365. serializationObject.materials.push(null);
  30366. }
  30367. }
  30368. return serializationObject;
  30369. };
  30370. return MultiMaterial;
  30371. }(BABYLON.Material));
  30372. BABYLON.MultiMaterial = MultiMaterial;
  30373. })(BABYLON || (BABYLON = {}));
  30374. //# sourceMappingURL=babylon.multiMaterial.js.map
  30375. var BABYLON;
  30376. (function (BABYLON) {
  30377. var SceneLoader = (function () {
  30378. function SceneLoader() {
  30379. }
  30380. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30381. get: function () {
  30382. return 0;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30388. get: function () {
  30389. return 1;
  30390. },
  30391. enumerable: true,
  30392. configurable: true
  30393. });
  30394. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30395. get: function () {
  30396. return 2;
  30397. },
  30398. enumerable: true,
  30399. configurable: true
  30400. });
  30401. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30402. get: function () {
  30403. return 3;
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30409. get: function () {
  30410. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30411. },
  30412. set: function (value) {
  30413. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30414. },
  30415. enumerable: true,
  30416. configurable: true
  30417. });
  30418. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30419. get: function () {
  30420. return SceneLoader._ShowLoadingScreen;
  30421. },
  30422. set: function (value) {
  30423. SceneLoader._ShowLoadingScreen = value;
  30424. },
  30425. enumerable: true,
  30426. configurable: true
  30427. });
  30428. Object.defineProperty(SceneLoader, "loggingLevel", {
  30429. get: function () {
  30430. return SceneLoader._loggingLevel;
  30431. },
  30432. set: function (value) {
  30433. SceneLoader._loggingLevel = value;
  30434. },
  30435. enumerable: true,
  30436. configurable: true
  30437. });
  30438. SceneLoader._getDefaultPlugin = function () {
  30439. return SceneLoader._registeredPlugins[".babylon"];
  30440. };
  30441. SceneLoader._getPluginForExtension = function (extension) {
  30442. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  30443. if (registeredPlugin) {
  30444. return registeredPlugin;
  30445. }
  30446. return SceneLoader._getDefaultPlugin();
  30447. };
  30448. SceneLoader._getPluginForFilename = function (sceneFilename) {
  30449. if (sceneFilename.name) {
  30450. sceneFilename = sceneFilename.name;
  30451. }
  30452. var dotPosition = sceneFilename.lastIndexOf(".");
  30453. var queryStringPosition = sceneFilename.indexOf("?");
  30454. if (queryStringPosition === -1) {
  30455. queryStringPosition = sceneFilename.length;
  30456. }
  30457. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  30458. return SceneLoader._getPluginForExtension(extension);
  30459. };
  30460. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  30461. SceneLoader._getDirectLoad = function (sceneFilename) {
  30462. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  30463. return sceneFilename.substr(5);
  30464. }
  30465. return null;
  30466. };
  30467. // Public functions
  30468. SceneLoader.GetPluginForExtension = function (extension) {
  30469. return SceneLoader._getPluginForExtension(extension).plugin;
  30470. };
  30471. SceneLoader.RegisterPlugin = function (plugin) {
  30472. if (typeof plugin.extensions === "string") {
  30473. var extension = plugin.extensions;
  30474. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30475. plugin: plugin,
  30476. isBinary: false
  30477. };
  30478. }
  30479. else {
  30480. var extensions = plugin.extensions;
  30481. Object.keys(extensions).forEach(function (extension) {
  30482. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  30483. plugin: plugin,
  30484. isBinary: extensions[extension].isBinary
  30485. };
  30486. });
  30487. }
  30488. };
  30489. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30490. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30491. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30492. return;
  30493. }
  30494. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30495. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30496. return;
  30497. }
  30498. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30499. var loadingToken = {};
  30500. scene._addPendingData(loadingToken);
  30501. var manifestChecked = function (success) {
  30502. scene.database = database;
  30503. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30504. var plugin = registeredPlugin.plugin;
  30505. var useArrayBuffer = registeredPlugin.isBinary;
  30506. var importMeshFromData = function (data) {
  30507. var meshes = [];
  30508. var particleSystems = [];
  30509. var skeletons = [];
  30510. try {
  30511. if (plugin.importMesh) {
  30512. var syncedPlugin = plugin;
  30513. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  30514. if (onerror) {
  30515. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30516. }
  30517. scene._removePendingData(loadingToken);
  30518. return;
  30519. }
  30520. if (onsuccess) {
  30521. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30522. onsuccess(meshes, particleSystems, skeletons);
  30523. scene._removePendingData(loadingToken);
  30524. }
  30525. }
  30526. else {
  30527. var asyncedPlugin = plugin;
  30528. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  30529. if (onsuccess) {
  30530. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  30531. onsuccess(meshes, particleSystems, skeletons);
  30532. scene._removePendingData(loadingToken);
  30533. }
  30534. }, function () {
  30535. if (onerror) {
  30536. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  30537. }
  30538. scene._removePendingData(loadingToken);
  30539. });
  30540. }
  30541. }
  30542. catch (e) {
  30543. if (onerror) {
  30544. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  30545. }
  30546. scene._removePendingData(loadingToken);
  30547. }
  30548. };
  30549. if (directLoad) {
  30550. importMeshFromData(directLoad);
  30551. return;
  30552. }
  30553. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  30554. importMeshFromData(data);
  30555. }, progressCallBack, database, useArrayBuffer);
  30556. };
  30557. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  30558. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30559. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30560. }
  30561. else {
  30562. // If the scene is a data stream or offline support is not enabled, it's a direct load
  30563. manifestChecked(true);
  30564. }
  30565. };
  30566. /**
  30567. * Load a scene
  30568. * @param rootUrl a string that defines the root url for scene and resources
  30569. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30570. * @param engine is the instance of BABYLON.Engine to use to create the scene
  30571. */
  30572. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  30573. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  30574. };
  30575. /**
  30576. * Append a scene
  30577. * @param rootUrl a string that defines the root url for scene and resources
  30578. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  30579. * @param scene is the instance of BABYLON.Scene to append to
  30580. */
  30581. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  30582. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  30583. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  30584. return;
  30585. }
  30586. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  30587. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  30588. var plugin = registeredPlugin.plugin;
  30589. var useArrayBuffer = registeredPlugin.isBinary;
  30590. var database;
  30591. var loadingToken = {};
  30592. scene._addPendingData(loadingToken);
  30593. if (SceneLoader.ShowLoadingScreen) {
  30594. scene.getEngine().displayLoadingUI();
  30595. }
  30596. var loadSceneFromData = function (data) {
  30597. scene.database = database;
  30598. if (plugin.load) {
  30599. var syncedPlugin = plugin;
  30600. if (!syncedPlugin.load(scene, data, rootUrl)) {
  30601. if (onerror) {
  30602. onerror(scene);
  30603. }
  30604. scene._removePendingData(loadingToken);
  30605. scene.getEngine().hideLoadingUI();
  30606. return;
  30607. }
  30608. if (onsuccess) {
  30609. onsuccess(scene);
  30610. }
  30611. scene._removePendingData(loadingToken);
  30612. }
  30613. else {
  30614. var asyncedPlugin = plugin;
  30615. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  30616. if (onsuccess) {
  30617. onsuccess(scene);
  30618. }
  30619. scene._removePendingData(loadingToken);
  30620. }, function () {
  30621. if (onerror) {
  30622. onerror(scene);
  30623. }
  30624. scene._removePendingData(loadingToken);
  30625. scene.getEngine().hideLoadingUI();
  30626. });
  30627. }
  30628. if (SceneLoader.ShowLoadingScreen) {
  30629. scene.executeWhenReady(function () {
  30630. scene.getEngine().hideLoadingUI();
  30631. });
  30632. }
  30633. };
  30634. var manifestChecked = function (success) {
  30635. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  30636. };
  30637. if (directLoad) {
  30638. loadSceneFromData(directLoad);
  30639. return;
  30640. }
  30641. if (rootUrl.indexOf("file:") === -1) {
  30642. if (scene.getEngine().enableOfflineSupport) {
  30643. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  30644. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  30645. }
  30646. else {
  30647. manifestChecked(true);
  30648. }
  30649. }
  30650. else {
  30651. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  30652. }
  30653. };
  30654. return SceneLoader;
  30655. }());
  30656. // Flags
  30657. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  30658. SceneLoader._ShowLoadingScreen = true;
  30659. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  30660. // Members
  30661. SceneLoader._registeredPlugins = {};
  30662. BABYLON.SceneLoader = SceneLoader;
  30663. ;
  30664. })(BABYLON || (BABYLON = {}));
  30665. //# sourceMappingURL=babylon.sceneLoader.js.map
  30666. var BABYLON;
  30667. (function (BABYLON) {
  30668. var Internals;
  30669. (function (Internals) {
  30670. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  30671. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30672. var parsedMaterial = parsedData.materials[index];
  30673. if (parsedMaterial.id === id) {
  30674. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30675. }
  30676. }
  30677. return null;
  30678. };
  30679. var isDescendantOf = function (mesh, names, hierarchyIds) {
  30680. names = (names instanceof Array) ? names : [names];
  30681. for (var i in names) {
  30682. if (mesh.name === names[i]) {
  30683. hierarchyIds.push(mesh.id);
  30684. return true;
  30685. }
  30686. }
  30687. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  30688. hierarchyIds.push(mesh.id);
  30689. return true;
  30690. }
  30691. return false;
  30692. };
  30693. var logOperation = function (operation, producer) {
  30694. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  30695. };
  30696. BABYLON.SceneLoader.RegisterPlugin({
  30697. extensions: ".babylon",
  30698. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  30699. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30700. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30701. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30702. // and avoid problems with multiple concurrent .babylon loads.
  30703. var log = "importMesh has failed JSON parse";
  30704. try {
  30705. var parsedData = JSON.parse(data);
  30706. log = "";
  30707. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30708. var loadedSkeletonsIds = [];
  30709. var loadedMaterialsIds = [];
  30710. var hierarchyIds = [];
  30711. var index;
  30712. var cache;
  30713. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  30714. var parsedMesh = parsedData.meshes[index];
  30715. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  30716. if (meshesNames instanceof Array) {
  30717. // Remove found mesh name from list.
  30718. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  30719. }
  30720. //Geometry?
  30721. if (parsedMesh.geometryId) {
  30722. //does the file contain geometries?
  30723. if (parsedData.geometries) {
  30724. //find the correct geometry and add it to the scene
  30725. var found = false;
  30726. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  30727. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  30728. return;
  30729. }
  30730. else {
  30731. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  30732. if (parsedGeometryData.id === parsedMesh.geometryId) {
  30733. switch (geometryType) {
  30734. case "boxes":
  30735. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  30736. break;
  30737. case "spheres":
  30738. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  30739. break;
  30740. case "cylinders":
  30741. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  30742. break;
  30743. case "toruses":
  30744. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  30745. break;
  30746. case "grounds":
  30747. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  30748. break;
  30749. case "planes":
  30750. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  30751. break;
  30752. case "torusKnots":
  30753. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  30754. break;
  30755. case "vertexData":
  30756. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  30757. break;
  30758. }
  30759. found = true;
  30760. }
  30761. });
  30762. }
  30763. });
  30764. if (!found) {
  30765. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  30766. }
  30767. }
  30768. }
  30769. // Material ?
  30770. if (parsedMesh.materialId) {
  30771. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  30772. if (!materialFound && parsedData.multiMaterials) {
  30773. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  30774. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  30775. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  30776. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  30777. var subMatId = parsedMultiMaterial.materials[matIndex];
  30778. loadedMaterialsIds.push(subMatId);
  30779. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  30780. log += "\n\tMaterial " + mat.toString(fullDetails);
  30781. }
  30782. loadedMaterialsIds.push(parsedMultiMaterial.id);
  30783. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30784. materialFound = true;
  30785. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  30786. break;
  30787. }
  30788. }
  30789. }
  30790. if (!materialFound) {
  30791. loadedMaterialsIds.push(parsedMesh.materialId);
  30792. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  30793. if (!mat) {
  30794. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  30795. }
  30796. else {
  30797. log += "\n\tMaterial " + mat.toString(fullDetails);
  30798. }
  30799. }
  30800. }
  30801. // Skeleton ?
  30802. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  30803. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  30804. if (!skeletonAlreadyLoaded) {
  30805. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  30806. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  30807. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  30808. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30809. skeletons.push(skeleton);
  30810. loadedSkeletonsIds.push(parsedSkeleton.id);
  30811. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  30812. }
  30813. }
  30814. }
  30815. }
  30816. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  30817. meshes.push(mesh);
  30818. log += "\n\tMesh " + mesh.toString(fullDetails);
  30819. }
  30820. }
  30821. // Connecting parents
  30822. var currentMesh;
  30823. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30824. currentMesh = scene.meshes[index];
  30825. if (currentMesh._waitingParentId) {
  30826. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  30827. currentMesh._waitingParentId = undefined;
  30828. }
  30829. }
  30830. // freeze and compute world matrix application
  30831. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  30832. currentMesh = scene.meshes[index];
  30833. if (currentMesh._waitingFreezeWorldMatrix) {
  30834. currentMesh.freezeWorldMatrix();
  30835. currentMesh._waitingFreezeWorldMatrix = undefined;
  30836. }
  30837. else {
  30838. currentMesh.computeWorldMatrix(true);
  30839. }
  30840. }
  30841. // Particles
  30842. if (parsedData.particleSystems) {
  30843. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  30844. var parsedParticleSystem = parsedData.particleSystems[index];
  30845. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  30846. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  30847. }
  30848. }
  30849. }
  30850. return true;
  30851. }
  30852. catch (err) {
  30853. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  30854. log = null;
  30855. throw err;
  30856. }
  30857. finally {
  30858. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  30859. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  30860. }
  30861. }
  30862. },
  30863. load: function (scene, data, rootUrl) {
  30864. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  30865. // when SceneLoader.debugLogging = true (default), or exception encountered.
  30866. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  30867. // and avoid problems with multiple concurrent .babylon loads.
  30868. var log = "importScene has failed JSON parse";
  30869. try {
  30870. var parsedData = JSON.parse(data);
  30871. log = "";
  30872. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  30873. // Scene
  30874. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  30875. scene.autoClear = parsedData.autoClear;
  30876. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  30877. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  30878. if (parsedData.gravity) {
  30879. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  30880. }
  30881. // Fog
  30882. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  30883. scene.fogMode = parsedData.fogMode;
  30884. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  30885. scene.fogStart = parsedData.fogStart;
  30886. scene.fogEnd = parsedData.fogEnd;
  30887. scene.fogDensity = parsedData.fogDensity;
  30888. log += "\tFog mode for scene: ";
  30889. switch (scene.fogMode) {
  30890. // getters not compiling, so using hardcoded
  30891. case 1:
  30892. log += "exp\n";
  30893. break;
  30894. case 2:
  30895. log += "exp2\n";
  30896. break;
  30897. case 3:
  30898. log += "linear\n";
  30899. break;
  30900. }
  30901. }
  30902. //Physics
  30903. if (parsedData.physicsEnabled) {
  30904. var physicsPlugin;
  30905. if (parsedData.physicsEngine === "cannon") {
  30906. physicsPlugin = new BABYLON.CannonJSPlugin();
  30907. }
  30908. else if (parsedData.physicsEngine === "oimo") {
  30909. physicsPlugin = new BABYLON.OimoJSPlugin();
  30910. }
  30911. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  30912. //else - default engine, which is currently oimo
  30913. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  30914. scene.enablePhysics(physicsGravity, physicsPlugin);
  30915. }
  30916. // Metadata
  30917. if (parsedData.metadata !== undefined) {
  30918. scene.metadata = parsedData.metadata;
  30919. }
  30920. //collisions, if defined. otherwise, default is true
  30921. if (parsedData.collisionsEnabled != undefined) {
  30922. scene.collisionsEnabled = parsedData.collisionsEnabled;
  30923. }
  30924. scene.workerCollisions = !!parsedData.workerCollisions;
  30925. var index;
  30926. var cache;
  30927. // Lights
  30928. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  30929. var parsedLight = parsedData.lights[index];
  30930. var light = BABYLON.Light.Parse(parsedLight, scene);
  30931. log += (index === 0 ? "\n\tLights:" : "");
  30932. log += "\n\t\t" + light.toString(fullDetails);
  30933. }
  30934. // Animations
  30935. if (parsedData.animations) {
  30936. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  30937. var parsedAnimation = parsedData.animations[index];
  30938. var animation = BABYLON.Animation.Parse(parsedAnimation);
  30939. scene.animations.push(animation);
  30940. log += (index === 0 ? "\n\tAnimations:" : "");
  30941. log += "\n\t\t" + animation.toString(fullDetails);
  30942. }
  30943. }
  30944. if (parsedData.autoAnimate) {
  30945. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  30946. }
  30947. // Materials
  30948. if (parsedData.materials) {
  30949. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  30950. var parsedMaterial = parsedData.materials[index];
  30951. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  30952. log += (index === 0 ? "\n\tMaterials:" : "");
  30953. log += "\n\t\t" + mat.toString(fullDetails);
  30954. }
  30955. }
  30956. if (parsedData.multiMaterials) {
  30957. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  30958. var parsedMultiMaterial = parsedData.multiMaterials[index];
  30959. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  30960. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  30961. log += "\n\t\t" + mmat.toString(fullDetails);
  30962. }
  30963. }
  30964. // Skeletons
  30965. if (parsedData.skeletons) {
  30966. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  30967. var parsedSkeleton = parsedData.skeletons[index];
  30968. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  30969. log += (index === 0 ? "\n\tSkeletons:" : "");
  30970. log += "\n\t\t" + skeleton.toString(fullDetails);
  30971. }
  30972. }
  30973. // Geometries
  30974. var geometries = parsedData.geometries;
  30975. if (geometries) {
  30976. // Boxes
  30977. var boxes = geometries.boxes;
  30978. if (boxes) {
  30979. for (index = 0, cache = boxes.length; index < cache; index++) {
  30980. var parsedBox = boxes[index];
  30981. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  30982. }
  30983. }
  30984. // Spheres
  30985. var spheres = geometries.spheres;
  30986. if (spheres) {
  30987. for (index = 0, cache = spheres.length; index < cache; index++) {
  30988. var parsedSphere = spheres[index];
  30989. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  30990. }
  30991. }
  30992. // Cylinders
  30993. var cylinders = geometries.cylinders;
  30994. if (cylinders) {
  30995. for (index = 0, cache = cylinders.length; index < cache; index++) {
  30996. var parsedCylinder = cylinders[index];
  30997. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  30998. }
  30999. }
  31000. // Toruses
  31001. var toruses = geometries.toruses;
  31002. if (toruses) {
  31003. for (index = 0, cache = toruses.length; index < cache; index++) {
  31004. var parsedTorus = toruses[index];
  31005. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  31006. }
  31007. }
  31008. // Grounds
  31009. var grounds = geometries.grounds;
  31010. if (grounds) {
  31011. for (index = 0, cache = grounds.length; index < cache; index++) {
  31012. var parsedGround = grounds[index];
  31013. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  31014. }
  31015. }
  31016. // Planes
  31017. var planes = geometries.planes;
  31018. if (planes) {
  31019. for (index = 0, cache = planes.length; index < cache; index++) {
  31020. var parsedPlane = planes[index];
  31021. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  31022. }
  31023. }
  31024. // TorusKnots
  31025. var torusKnots = geometries.torusKnots;
  31026. if (torusKnots) {
  31027. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  31028. var parsedTorusKnot = torusKnots[index];
  31029. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  31030. }
  31031. }
  31032. // VertexData
  31033. var vertexData = geometries.vertexData;
  31034. if (vertexData) {
  31035. for (index = 0, cache = vertexData.length; index < cache; index++) {
  31036. var parsedVertexData = vertexData[index];
  31037. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  31038. }
  31039. }
  31040. }
  31041. // Meshes
  31042. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31043. var parsedMesh = parsedData.meshes[index];
  31044. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31045. log += (index === 0 ? "\n\tMeshes:" : "");
  31046. log += "\n\t\t" + mesh.toString(fullDetails);
  31047. }
  31048. // Cameras
  31049. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  31050. var parsedCamera = parsedData.cameras[index];
  31051. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  31052. log += (index === 0 ? "\n\tCameras:" : "");
  31053. log += "\n\t\t" + camera.toString(fullDetails);
  31054. }
  31055. if (parsedData.activeCameraID) {
  31056. scene.setActiveCameraByID(parsedData.activeCameraID);
  31057. }
  31058. // Browsing all the graph to connect the dots
  31059. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  31060. var camera = scene.cameras[index];
  31061. if (camera._waitingParentId) {
  31062. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  31063. camera._waitingParentId = undefined;
  31064. }
  31065. }
  31066. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  31067. var light = scene.lights[index];
  31068. if (light._waitingParentId) {
  31069. light.parent = scene.getLastEntryByID(light._waitingParentId);
  31070. light._waitingParentId = undefined;
  31071. }
  31072. }
  31073. // Sounds
  31074. var loadedSounds = [];
  31075. var loadedSound;
  31076. if (BABYLON.AudioEngine && parsedData.sounds) {
  31077. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  31078. var parsedSound = parsedData.sounds[index];
  31079. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31080. if (!parsedSound.url)
  31081. parsedSound.url = parsedSound.name;
  31082. if (!loadedSounds[parsedSound.url]) {
  31083. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  31084. loadedSounds[parsedSound.url] = loadedSound;
  31085. }
  31086. else {
  31087. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  31088. }
  31089. }
  31090. else {
  31091. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  31092. }
  31093. }
  31094. }
  31095. loadedSounds = [];
  31096. // Connect parents & children and parse actions
  31097. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31098. var mesh = scene.meshes[index];
  31099. if (mesh._waitingParentId) {
  31100. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  31101. mesh._waitingParentId = undefined;
  31102. }
  31103. if (mesh._waitingActions) {
  31104. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  31105. mesh._waitingActions = undefined;
  31106. }
  31107. }
  31108. // freeze world matrix application
  31109. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31110. var currentMesh = scene.meshes[index];
  31111. if (currentMesh._waitingFreezeWorldMatrix) {
  31112. currentMesh.freezeWorldMatrix();
  31113. currentMesh._waitingFreezeWorldMatrix = undefined;
  31114. }
  31115. else {
  31116. currentMesh.computeWorldMatrix(true);
  31117. }
  31118. }
  31119. // Particles Systems
  31120. if (parsedData.particleSystems) {
  31121. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31122. var parsedParticleSystem = parsedData.particleSystems[index];
  31123. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  31124. }
  31125. }
  31126. // Lens flares
  31127. if (parsedData.lensFlareSystems) {
  31128. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  31129. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  31130. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  31131. }
  31132. }
  31133. // Shadows
  31134. if (parsedData.shadowGenerators) {
  31135. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  31136. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  31137. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  31138. }
  31139. }
  31140. // Actions (scene)
  31141. if (parsedData.actions) {
  31142. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  31143. }
  31144. // Finish
  31145. return true;
  31146. }
  31147. catch (err) {
  31148. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  31149. log = null;
  31150. throw err;
  31151. }
  31152. finally {
  31153. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31154. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31155. }
  31156. }
  31157. }
  31158. });
  31159. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31160. })(BABYLON || (BABYLON = {}));
  31161. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  31162. var BABYLON;
  31163. (function (BABYLON) {
  31164. var SpriteManager = (function () {
  31165. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  31166. if (epsilon === void 0) { epsilon = 0.01; }
  31167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31168. this.name = name;
  31169. this.sprites = new Array();
  31170. this.renderingGroupId = 0;
  31171. this.layerMask = 0x0FFFFFFF;
  31172. this.fogEnabled = true;
  31173. this.isPickable = false;
  31174. /**
  31175. * An event triggered when the manager is disposed.
  31176. * @type {BABYLON.Observable}
  31177. */
  31178. this.onDisposeObservable = new BABYLON.Observable();
  31179. this._vertexBuffers = {};
  31180. this._capacity = capacity;
  31181. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  31182. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31183. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31184. if (cellSize.width && cellSize.height) {
  31185. this.cellWidth = cellSize.width;
  31186. this.cellHeight = cellSize.height;
  31187. }
  31188. else if (cellSize !== undefined) {
  31189. this.cellWidth = cellSize;
  31190. this.cellHeight = cellSize;
  31191. }
  31192. else {
  31193. return;
  31194. }
  31195. this._epsilon = epsilon;
  31196. this._scene = scene;
  31197. this._scene.spriteManagers.push(this);
  31198. var indices = [];
  31199. var index = 0;
  31200. for (var count = 0; count < capacity; count++) {
  31201. indices.push(index);
  31202. indices.push(index + 1);
  31203. indices.push(index + 2);
  31204. indices.push(index);
  31205. indices.push(index + 2);
  31206. indices.push(index + 3);
  31207. index += 4;
  31208. }
  31209. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31210. // VBO
  31211. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31212. this._vertexData = new Float32Array(capacity * 16 * 4);
  31213. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31214. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31215. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31216. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31217. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31218. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31219. this._vertexBuffers["options"] = options;
  31220. this._vertexBuffers["cellInfo"] = cellInfo;
  31221. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31222. // Effects
  31223. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31224. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31225. }
  31226. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31227. set: function (callback) {
  31228. if (this._onDisposeObserver) {
  31229. this.onDisposeObservable.remove(this._onDisposeObserver);
  31230. }
  31231. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31232. },
  31233. enumerable: true,
  31234. configurable: true
  31235. });
  31236. Object.defineProperty(SpriteManager.prototype, "texture", {
  31237. get: function () {
  31238. return this._spriteTexture;
  31239. },
  31240. set: function (value) {
  31241. this._spriteTexture = value;
  31242. },
  31243. enumerable: true,
  31244. configurable: true
  31245. });
  31246. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31247. var arrayOffset = index * 16;
  31248. if (offsetX === 0)
  31249. offsetX = this._epsilon;
  31250. else if (offsetX === 1)
  31251. offsetX = 1 - this._epsilon;
  31252. if (offsetY === 0)
  31253. offsetY = this._epsilon;
  31254. else if (offsetY === 1)
  31255. offsetY = 1 - this._epsilon;
  31256. this._vertexData[arrayOffset] = sprite.position.x;
  31257. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31258. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31259. this._vertexData[arrayOffset + 3] = sprite.angle;
  31260. this._vertexData[arrayOffset + 4] = sprite.width;
  31261. this._vertexData[arrayOffset + 5] = sprite.height;
  31262. this._vertexData[arrayOffset + 6] = offsetX;
  31263. this._vertexData[arrayOffset + 7] = offsetY;
  31264. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31265. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31266. var offset = (sprite.cellIndex / rowSize) >> 0;
  31267. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31268. this._vertexData[arrayOffset + 11] = offset;
  31269. // Color
  31270. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31271. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31272. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31273. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31274. };
  31275. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31276. var count = Math.min(this._capacity, this.sprites.length);
  31277. var min = BABYLON.Vector3.Zero();
  31278. var max = BABYLON.Vector3.Zero();
  31279. var distance = Number.MAX_VALUE;
  31280. var currentSprite;
  31281. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31282. var cameraView = camera.getViewMatrix();
  31283. for (var index = 0; index < count; index++) {
  31284. var sprite = this.sprites[index];
  31285. if (!sprite) {
  31286. continue;
  31287. }
  31288. if (predicate) {
  31289. if (!predicate(sprite)) {
  31290. continue;
  31291. }
  31292. }
  31293. else if (!sprite.isPickable) {
  31294. continue;
  31295. }
  31296. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31297. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31298. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31299. if (ray.intersectsBoxMinMax(min, max)) {
  31300. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31301. if (distance > currentDistance) {
  31302. distance = currentDistance;
  31303. currentSprite = sprite;
  31304. if (fastCheck) {
  31305. break;
  31306. }
  31307. }
  31308. }
  31309. }
  31310. if (currentSprite) {
  31311. var result = new BABYLON.PickingInfo();
  31312. result.hit = true;
  31313. result.pickedSprite = currentSprite;
  31314. result.distance = distance;
  31315. return result;
  31316. }
  31317. return null;
  31318. };
  31319. SpriteManager.prototype.render = function () {
  31320. // Check
  31321. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31322. return;
  31323. var engine = this._scene.getEngine();
  31324. var baseSize = this._spriteTexture.getBaseSize();
  31325. // Sprites
  31326. var deltaTime = engine.getDeltaTime();
  31327. var max = Math.min(this._capacity, this.sprites.length);
  31328. var rowSize = baseSize.width / this.cellWidth;
  31329. var offset = 0;
  31330. for (var index = 0; index < max; index++) {
  31331. var sprite = this.sprites[index];
  31332. if (!sprite) {
  31333. continue;
  31334. }
  31335. sprite._animate(deltaTime);
  31336. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31337. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31338. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31339. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31340. }
  31341. this._buffer.update(this._vertexData);
  31342. // Render
  31343. var effect = this._effectBase;
  31344. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31345. effect = this._effectFog;
  31346. }
  31347. engine.enableEffect(effect);
  31348. var viewMatrix = this._scene.getViewMatrix();
  31349. effect.setTexture("diffuseSampler", this._spriteTexture);
  31350. effect.setMatrix("view", viewMatrix);
  31351. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31352. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31353. // Fog
  31354. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31355. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31356. effect.setColor3("vFogColor", this._scene.fogColor);
  31357. }
  31358. // VBOs
  31359. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31360. // Draw order
  31361. engine.setDepthFunctionToLessOrEqual();
  31362. effect.setBool("alphaTest", true);
  31363. engine.setColorWrite(false);
  31364. engine.draw(true, 0, max * 6);
  31365. engine.setColorWrite(true);
  31366. effect.setBool("alphaTest", false);
  31367. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31368. engine.draw(true, 0, max * 6);
  31369. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31370. };
  31371. SpriteManager.prototype.dispose = function () {
  31372. if (this._buffer) {
  31373. this._buffer.dispose();
  31374. this._buffer = null;
  31375. }
  31376. if (this._indexBuffer) {
  31377. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31378. this._indexBuffer = null;
  31379. }
  31380. if (this._spriteTexture) {
  31381. this._spriteTexture.dispose();
  31382. this._spriteTexture = null;
  31383. }
  31384. // Remove from scene
  31385. var index = this._scene.spriteManagers.indexOf(this);
  31386. this._scene.spriteManagers.splice(index, 1);
  31387. // Callback
  31388. this.onDisposeObservable.notifyObservers(this);
  31389. this.onDisposeObservable.clear();
  31390. };
  31391. return SpriteManager;
  31392. }());
  31393. BABYLON.SpriteManager = SpriteManager;
  31394. })(BABYLON || (BABYLON = {}));
  31395. //# sourceMappingURL=babylon.spriteManager.js.map
  31396. var BABYLON;
  31397. (function (BABYLON) {
  31398. var Sprite = (function () {
  31399. function Sprite(name, manager) {
  31400. this.name = name;
  31401. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31402. this.width = 1.0;
  31403. this.height = 1.0;
  31404. this.angle = 0;
  31405. this.cellIndex = 0;
  31406. this.invertU = 0;
  31407. this.invertV = 0;
  31408. this.animations = new Array();
  31409. this.isPickable = false;
  31410. this._animationStarted = false;
  31411. this._loopAnimation = false;
  31412. this._fromIndex = 0;
  31413. this._toIndex = 0;
  31414. this._delay = 0;
  31415. this._direction = 1;
  31416. this._frameCount = 0;
  31417. this._time = 0;
  31418. this._manager = manager;
  31419. this._manager.sprites.push(this);
  31420. this.position = BABYLON.Vector3.Zero();
  31421. }
  31422. Object.defineProperty(Sprite.prototype, "size", {
  31423. get: function () {
  31424. return this.width;
  31425. },
  31426. set: function (value) {
  31427. this.width = value;
  31428. this.height = value;
  31429. },
  31430. enumerable: true,
  31431. configurable: true
  31432. });
  31433. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  31434. this._fromIndex = from;
  31435. this._toIndex = to;
  31436. this._loopAnimation = loop;
  31437. this._delay = delay;
  31438. this._animationStarted = true;
  31439. this._direction = from < to ? 1 : -1;
  31440. this.cellIndex = from;
  31441. this._time = 0;
  31442. this._onAnimationEnd = onAnimationEnd;
  31443. };
  31444. Sprite.prototype.stopAnimation = function () {
  31445. this._animationStarted = false;
  31446. };
  31447. Sprite.prototype._animate = function (deltaTime) {
  31448. if (!this._animationStarted)
  31449. return;
  31450. this._time += deltaTime;
  31451. if (this._time > this._delay) {
  31452. this._time = this._time % this._delay;
  31453. this.cellIndex += this._direction;
  31454. if (this.cellIndex === this._toIndex) {
  31455. if (this._loopAnimation) {
  31456. this.cellIndex = this._fromIndex;
  31457. }
  31458. else {
  31459. this._animationStarted = false;
  31460. if (this._onAnimationEnd) {
  31461. this._onAnimationEnd();
  31462. }
  31463. if (this.disposeWhenFinishedAnimating) {
  31464. this.dispose();
  31465. }
  31466. }
  31467. }
  31468. }
  31469. };
  31470. Sprite.prototype.dispose = function () {
  31471. for (var i = 0; i < this._manager.sprites.length; i++) {
  31472. if (this._manager.sprites[i] == this) {
  31473. this._manager.sprites.splice(i, 1);
  31474. }
  31475. }
  31476. };
  31477. return Sprite;
  31478. }());
  31479. BABYLON.Sprite = Sprite;
  31480. })(BABYLON || (BABYLON = {}));
  31481. //# sourceMappingURL=babylon.sprite.js.map
  31482. var BABYLON;
  31483. (function (BABYLON) {
  31484. var Layer = (function () {
  31485. function Layer(name, imgUrl, scene, isBackground, color) {
  31486. this.name = name;
  31487. this.scale = new BABYLON.Vector2(1, 1);
  31488. this.offset = new BABYLON.Vector2(0, 0);
  31489. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  31490. this._vertexBuffers = {};
  31491. // Events
  31492. /**
  31493. * An event triggered when the layer is disposed.
  31494. * @type {BABYLON.Observable}
  31495. */
  31496. this.onDisposeObservable = new BABYLON.Observable();
  31497. /**
  31498. * An event triggered before rendering the scene
  31499. * @type {BABYLON.Observable}
  31500. */
  31501. this.onBeforeRenderObservable = new BABYLON.Observable();
  31502. /**
  31503. * An event triggered after rendering the scene
  31504. * @type {BABYLON.Observable}
  31505. */
  31506. this.onAfterRenderObservable = new BABYLON.Observable();
  31507. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  31508. this.isBackground = isBackground === undefined ? true : isBackground;
  31509. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  31510. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31511. this._scene.layers.push(this);
  31512. var engine = scene.getEngine();
  31513. // VBO
  31514. var vertices = [];
  31515. vertices.push(1, 1);
  31516. vertices.push(-1, 1);
  31517. vertices.push(-1, -1);
  31518. vertices.push(1, -1);
  31519. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31520. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  31521. // Indices
  31522. var indices = [];
  31523. indices.push(0);
  31524. indices.push(1);
  31525. indices.push(2);
  31526. indices.push(0);
  31527. indices.push(2);
  31528. indices.push(3);
  31529. this._indexBuffer = engine.createIndexBuffer(indices);
  31530. // Effects
  31531. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  31532. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  31533. }
  31534. Object.defineProperty(Layer.prototype, "onDispose", {
  31535. set: function (callback) {
  31536. if (this._onDisposeObserver) {
  31537. this.onDisposeObservable.remove(this._onDisposeObserver);
  31538. }
  31539. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31540. },
  31541. enumerable: true,
  31542. configurable: true
  31543. });
  31544. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  31545. set: function (callback) {
  31546. if (this._onBeforeRenderObserver) {
  31547. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31548. }
  31549. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Layer.prototype, "onAfterRender", {
  31555. set: function (callback) {
  31556. if (this._onAfterRenderObserver) {
  31557. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31558. }
  31559. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. Layer.prototype.render = function () {
  31565. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  31566. // Check
  31567. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  31568. return;
  31569. var engine = this._scene.getEngine();
  31570. this.onBeforeRenderObservable.notifyObservers(this);
  31571. // Render
  31572. engine.enableEffect(currentEffect);
  31573. engine.setState(false);
  31574. // Texture
  31575. currentEffect.setTexture("textureSampler", this.texture);
  31576. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  31577. // Color
  31578. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  31579. // Scale / offset
  31580. currentEffect.setVector2("offset", this.offset);
  31581. currentEffect.setVector2("scale", this.scale);
  31582. // VBOs
  31583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  31584. // Draw order
  31585. if (!this.alphaTest) {
  31586. engine.setAlphaMode(this.alphaBlendingMode);
  31587. engine.draw(true, 0, 6);
  31588. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31589. }
  31590. else {
  31591. engine.draw(true, 0, 6);
  31592. }
  31593. this.onAfterRenderObservable.notifyObservers(this);
  31594. };
  31595. Layer.prototype.dispose = function () {
  31596. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31597. if (vertexBuffer) {
  31598. vertexBuffer.dispose();
  31599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31600. }
  31601. if (this._indexBuffer) {
  31602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31603. this._indexBuffer = null;
  31604. }
  31605. if (this.texture) {
  31606. this.texture.dispose();
  31607. this.texture = null;
  31608. }
  31609. // Remove from scene
  31610. var index = this._scene.layers.indexOf(this);
  31611. this._scene.layers.splice(index, 1);
  31612. // Callback
  31613. this.onDisposeObservable.notifyObservers(this);
  31614. this.onDisposeObservable.clear();
  31615. this.onAfterRenderObservable.clear();
  31616. this.onBeforeRenderObservable.clear();
  31617. };
  31618. return Layer;
  31619. }());
  31620. BABYLON.Layer = Layer;
  31621. })(BABYLON || (BABYLON = {}));
  31622. //# sourceMappingURL=babylon.layer.js.map
  31623. var BABYLON;
  31624. (function (BABYLON) {
  31625. var Particle = (function () {
  31626. function Particle() {
  31627. this.position = BABYLON.Vector3.Zero();
  31628. this.direction = BABYLON.Vector3.Zero();
  31629. this.color = new BABYLON.Color4(0, 0, 0, 0);
  31630. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  31631. this.lifeTime = 1.0;
  31632. this.age = 0;
  31633. this.size = 0;
  31634. this.angle = 0;
  31635. this.angularSpeed = 0;
  31636. }
  31637. Particle.prototype.copyTo = function (other) {
  31638. other.position.copyFrom(this.position);
  31639. other.direction.copyFrom(this.direction);
  31640. other.color.copyFrom(this.color);
  31641. other.colorStep.copyFrom(this.colorStep);
  31642. other.lifeTime = this.lifeTime;
  31643. other.age = this.age;
  31644. other.size = this.size;
  31645. other.angle = this.angle;
  31646. other.angularSpeed = this.angularSpeed;
  31647. };
  31648. return Particle;
  31649. }());
  31650. BABYLON.Particle = Particle;
  31651. })(BABYLON || (BABYLON = {}));
  31652. //# sourceMappingURL=babylon.particle.js.map
  31653. var BABYLON;
  31654. (function (BABYLON) {
  31655. var randomNumber = function (min, max) {
  31656. if (min === max) {
  31657. return (min);
  31658. }
  31659. var random = Math.random();
  31660. return ((random * (max - min)) + min);
  31661. };
  31662. var ParticleSystem = (function () {
  31663. function ParticleSystem(name, capacity, scene, customEffect) {
  31664. var _this = this;
  31665. this.name = name;
  31666. // Members
  31667. this.animations = [];
  31668. this.renderingGroupId = 0;
  31669. this.emitter = null;
  31670. this.emitRate = 10;
  31671. this.manualEmitCount = -1;
  31672. this.updateSpeed = 0.01;
  31673. this.targetStopDuration = 0;
  31674. this.disposeOnStop = false;
  31675. this.minEmitPower = 1;
  31676. this.maxEmitPower = 1;
  31677. this.minLifeTime = 1;
  31678. this.maxLifeTime = 1;
  31679. this.minSize = 1;
  31680. this.maxSize = 1;
  31681. this.minAngularSpeed = 0;
  31682. this.maxAngularSpeed = 0;
  31683. this.layerMask = 0x0FFFFFFF;
  31684. this.customShader = null;
  31685. this.preventAutoStart = false;
  31686. /**
  31687. * An event triggered when the system is disposed.
  31688. * @type {BABYLON.Observable}
  31689. */
  31690. this.onDisposeObservable = new BABYLON.Observable();
  31691. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  31692. this.forceDepthWrite = false;
  31693. this.gravity = BABYLON.Vector3.Zero();
  31694. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  31695. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  31696. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  31697. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31698. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31699. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31700. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  31701. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31702. this.particles = new Array();
  31703. this._stockParticles = new Array();
  31704. this._newPartsExcess = 0;
  31705. this._vertexBuffers = {};
  31706. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  31707. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  31708. this._scaledDirection = BABYLON.Vector3.Zero();
  31709. this._scaledGravity = BABYLON.Vector3.Zero();
  31710. this._currentRenderId = -1;
  31711. this._started = false;
  31712. this._stopped = false;
  31713. this._actualFrame = 0;
  31714. this.id = name;
  31715. this._capacity = capacity;
  31716. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31717. this._customEffect = customEffect;
  31718. scene.particleSystems.push(this);
  31719. var indices = [];
  31720. var index = 0;
  31721. for (var count = 0; count < capacity; count++) {
  31722. indices.push(index);
  31723. indices.push(index + 1);
  31724. indices.push(index + 2);
  31725. indices.push(index);
  31726. indices.push(index + 2);
  31727. indices.push(index + 3);
  31728. index += 4;
  31729. }
  31730. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31731. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  31732. this._vertexData = new Float32Array(capacity * 11 * 4);
  31733. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  31734. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  31735. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  31736. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  31737. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31738. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31739. this._vertexBuffers["options"] = options;
  31740. // Default behaviors
  31741. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  31742. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  31743. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  31744. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  31745. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  31746. };
  31747. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  31748. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  31749. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  31750. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  31751. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  31752. };
  31753. this.updateFunction = function (particles) {
  31754. for (var index = 0; index < particles.length; index++) {
  31755. var particle = particles[index];
  31756. particle.age += _this._scaledUpdateSpeed;
  31757. if (particle.age >= particle.lifeTime) {
  31758. _this.recycleParticle(particle);
  31759. index--;
  31760. continue;
  31761. }
  31762. else {
  31763. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  31764. particle.color.addInPlace(_this._scaledColorStep);
  31765. if (particle.color.a < 0)
  31766. particle.color.a = 0;
  31767. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  31768. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  31769. particle.position.addInPlace(_this._scaledDirection);
  31770. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  31771. particle.direction.addInPlace(_this._scaledGravity);
  31772. }
  31773. }
  31774. };
  31775. }
  31776. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  31777. set: function (callback) {
  31778. if (this._onDisposeObserver) {
  31779. this.onDisposeObservable.remove(this._onDisposeObserver);
  31780. }
  31781. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31782. },
  31783. enumerable: true,
  31784. configurable: true
  31785. });
  31786. ParticleSystem.prototype.recycleParticle = function (particle) {
  31787. var lastParticle = this.particles.pop();
  31788. if (lastParticle !== particle) {
  31789. lastParticle.copyTo(particle);
  31790. this._stockParticles.push(lastParticle);
  31791. }
  31792. };
  31793. ParticleSystem.prototype.getCapacity = function () {
  31794. return this._capacity;
  31795. };
  31796. ParticleSystem.prototype.isAlive = function () {
  31797. return this._alive;
  31798. };
  31799. ParticleSystem.prototype.isStarted = function () {
  31800. return this._started;
  31801. };
  31802. ParticleSystem.prototype.start = function () {
  31803. this._started = true;
  31804. this._stopped = false;
  31805. this._actualFrame = 0;
  31806. };
  31807. ParticleSystem.prototype.stop = function () {
  31808. this._stopped = true;
  31809. };
  31810. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  31811. var offset = index * 11;
  31812. this._vertexData[offset] = particle.position.x;
  31813. this._vertexData[offset + 1] = particle.position.y;
  31814. this._vertexData[offset + 2] = particle.position.z;
  31815. this._vertexData[offset + 3] = particle.color.r;
  31816. this._vertexData[offset + 4] = particle.color.g;
  31817. this._vertexData[offset + 5] = particle.color.b;
  31818. this._vertexData[offset + 6] = particle.color.a;
  31819. this._vertexData[offset + 7] = particle.angle;
  31820. this._vertexData[offset + 8] = particle.size;
  31821. this._vertexData[offset + 9] = offsetX;
  31822. this._vertexData[offset + 10] = offsetY;
  31823. };
  31824. ParticleSystem.prototype._update = function (newParticles) {
  31825. // Update current
  31826. this._alive = this.particles.length > 0;
  31827. this.updateFunction(this.particles);
  31828. // Add new ones
  31829. var worldMatrix;
  31830. if (this.emitter.position) {
  31831. worldMatrix = this.emitter.getWorldMatrix();
  31832. }
  31833. else {
  31834. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  31835. }
  31836. var particle;
  31837. for (var index = 0; index < newParticles; index++) {
  31838. if (this.particles.length === this._capacity) {
  31839. break;
  31840. }
  31841. if (this._stockParticles.length !== 0) {
  31842. particle = this._stockParticles.pop();
  31843. particle.age = 0;
  31844. }
  31845. else {
  31846. particle = new BABYLON.Particle();
  31847. }
  31848. this.particles.push(particle);
  31849. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  31850. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  31851. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  31852. particle.size = randomNumber(this.minSize, this.maxSize);
  31853. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  31854. this.startPositionFunction(worldMatrix, particle.position, particle);
  31855. var step = randomNumber(0, 1.0);
  31856. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  31857. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  31858. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  31859. }
  31860. };
  31861. ParticleSystem.prototype._getEffect = function () {
  31862. if (this._customEffect) {
  31863. return this._customEffect;
  31864. }
  31865. ;
  31866. var defines = [];
  31867. if (this._scene.clipPlane) {
  31868. defines.push("#define CLIPPLANE");
  31869. }
  31870. // Effect
  31871. var join = defines.join("\n");
  31872. if (this._cachedDefines !== join) {
  31873. this._cachedDefines = join;
  31874. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  31875. }
  31876. return this._effect;
  31877. };
  31878. ParticleSystem.prototype.animate = function () {
  31879. if (!this._started)
  31880. return;
  31881. var effect = this._getEffect();
  31882. // Check
  31883. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  31884. return;
  31885. if (this._currentRenderId === this._scene.getRenderId()) {
  31886. return;
  31887. }
  31888. this._currentRenderId = this._scene.getRenderId();
  31889. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  31890. // determine the number of particles we need to create
  31891. var newParticles;
  31892. if (this.manualEmitCount > -1) {
  31893. newParticles = this.manualEmitCount;
  31894. this._newPartsExcess = 0;
  31895. this.manualEmitCount = 0;
  31896. }
  31897. else {
  31898. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  31899. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  31900. }
  31901. if (this._newPartsExcess > 1.0) {
  31902. newParticles += this._newPartsExcess >> 0;
  31903. this._newPartsExcess -= this._newPartsExcess >> 0;
  31904. }
  31905. this._alive = false;
  31906. if (!this._stopped) {
  31907. this._actualFrame += this._scaledUpdateSpeed;
  31908. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  31909. this.stop();
  31910. }
  31911. else {
  31912. newParticles = 0;
  31913. }
  31914. this._update(newParticles);
  31915. // Stopped?
  31916. if (this._stopped) {
  31917. if (!this._alive) {
  31918. this._started = false;
  31919. if (this.disposeOnStop) {
  31920. this._scene._toBeDisposed.push(this);
  31921. }
  31922. }
  31923. }
  31924. // Update VBO
  31925. var offset = 0;
  31926. for (var index = 0; index < this.particles.length; index++) {
  31927. var particle = this.particles[index];
  31928. this._appendParticleVertex(offset++, particle, 0, 0);
  31929. this._appendParticleVertex(offset++, particle, 1, 0);
  31930. this._appendParticleVertex(offset++, particle, 1, 1);
  31931. this._appendParticleVertex(offset++, particle, 0, 1);
  31932. }
  31933. this._vertexBuffer.update(this._vertexData);
  31934. };
  31935. ParticleSystem.prototype.render = function () {
  31936. var effect = this._getEffect();
  31937. // Check
  31938. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  31939. return 0;
  31940. var engine = this._scene.getEngine();
  31941. // Render
  31942. engine.enableEffect(effect);
  31943. engine.setState(false);
  31944. var viewMatrix = this._scene.getViewMatrix();
  31945. effect.setTexture("diffuseSampler", this.particleTexture);
  31946. effect.setMatrix("view", viewMatrix);
  31947. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31948. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  31949. if (this._scene.clipPlane) {
  31950. var clipPlane = this._scene.clipPlane;
  31951. var invView = viewMatrix.clone();
  31952. invView.invert();
  31953. effect.setMatrix("invView", invView);
  31954. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  31955. }
  31956. // VBOs
  31957. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31958. // Draw order
  31959. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  31960. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  31961. }
  31962. else {
  31963. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31964. }
  31965. if (this.forceDepthWrite) {
  31966. engine.setDepthWrite(true);
  31967. }
  31968. engine.draw(true, 0, this.particles.length * 6);
  31969. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31970. return this.particles.length;
  31971. };
  31972. ParticleSystem.prototype.dispose = function () {
  31973. if (this._vertexBuffer) {
  31974. this._vertexBuffer.dispose();
  31975. this._vertexBuffer = null;
  31976. }
  31977. if (this._indexBuffer) {
  31978. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31979. this._indexBuffer = null;
  31980. }
  31981. if (this.particleTexture) {
  31982. this.particleTexture.dispose();
  31983. this.particleTexture = null;
  31984. }
  31985. // Remove from scene
  31986. var index = this._scene.particleSystems.indexOf(this);
  31987. this._scene.particleSystems.splice(index, 1);
  31988. // Callback
  31989. this.onDisposeObservable.notifyObservers(this);
  31990. this.onDisposeObservable.clear();
  31991. };
  31992. // Clone
  31993. ParticleSystem.prototype.clone = function (name, newEmitter) {
  31994. var custom = null;
  31995. var program = null;
  31996. if (this.customShader != null) {
  31997. program = this.customShader;
  31998. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  31999. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32000. }
  32001. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  32002. result.customShader = program;
  32003. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  32004. if (newEmitter === undefined) {
  32005. newEmitter = this.emitter;
  32006. }
  32007. result.emitter = newEmitter;
  32008. if (this.particleTexture) {
  32009. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  32010. }
  32011. if (!this.preventAutoStart) {
  32012. result.start();
  32013. }
  32014. return result;
  32015. };
  32016. ParticleSystem.prototype.serialize = function () {
  32017. var serializationObject = {};
  32018. serializationObject.name = this.name;
  32019. serializationObject.id = this.id;
  32020. // Emitter
  32021. if (this.emitter.position) {
  32022. serializationObject.emitterId = this.emitter.id;
  32023. }
  32024. else {
  32025. serializationObject.emitter = this.emitter.asArray();
  32026. }
  32027. serializationObject.capacity = this.getCapacity();
  32028. if (this.particleTexture) {
  32029. serializationObject.textureName = this.particleTexture.name;
  32030. }
  32031. // Animations
  32032. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32033. // Particle system
  32034. serializationObject.minAngularSpeed = this.minAngularSpeed;
  32035. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  32036. serializationObject.minSize = this.minSize;
  32037. serializationObject.maxSize = this.maxSize;
  32038. serializationObject.minEmitPower = this.minEmitPower;
  32039. serializationObject.maxEmitPower = this.maxEmitPower;
  32040. serializationObject.minLifeTime = this.minLifeTime;
  32041. serializationObject.maxLifeTime = this.maxLifeTime;
  32042. serializationObject.emitRate = this.emitRate;
  32043. serializationObject.minEmitBox = this.minEmitBox.asArray();
  32044. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  32045. serializationObject.gravity = this.gravity.asArray();
  32046. serializationObject.direction1 = this.direction1.asArray();
  32047. serializationObject.direction2 = this.direction2.asArray();
  32048. serializationObject.color1 = this.color1.asArray();
  32049. serializationObject.color2 = this.color2.asArray();
  32050. serializationObject.colorDead = this.colorDead.asArray();
  32051. serializationObject.updateSpeed = this.updateSpeed;
  32052. serializationObject.targetStopDuration = this.targetStopDuration;
  32053. serializationObject.textureMask = this.textureMask.asArray();
  32054. serializationObject.blendMode = this.blendMode;
  32055. serializationObject.customShader = this.customShader;
  32056. serializationObject.preventAutoStart = this.preventAutoStart;
  32057. return serializationObject;
  32058. };
  32059. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  32060. var name = parsedParticleSystem.name;
  32061. var custom = null;
  32062. var program = null;
  32063. if (parsedParticleSystem.customShader) {
  32064. program = parsedParticleSystem.customShader;
  32065. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32066. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32067. }
  32068. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  32069. particleSystem.customShader = program;
  32070. if (parsedParticleSystem.id) {
  32071. particleSystem.id = parsedParticleSystem.id;
  32072. }
  32073. // Auto start
  32074. if (parsedParticleSystem.preventAutoStart) {
  32075. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  32076. }
  32077. // Texture
  32078. if (parsedParticleSystem.textureName) {
  32079. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  32080. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  32081. }
  32082. // Emitter
  32083. if (parsedParticleSystem.emitterId) {
  32084. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  32085. }
  32086. else {
  32087. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  32088. }
  32089. // Animations
  32090. if (parsedParticleSystem.animations) {
  32091. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  32092. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  32093. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32094. }
  32095. }
  32096. if (parsedParticleSystem.autoAnimate) {
  32097. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  32098. }
  32099. // Particle system
  32100. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  32101. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  32102. particleSystem.minSize = parsedParticleSystem.minSize;
  32103. particleSystem.maxSize = parsedParticleSystem.maxSize;
  32104. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  32105. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  32106. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  32107. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  32108. particleSystem.emitRate = parsedParticleSystem.emitRate;
  32109. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  32110. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  32111. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  32112. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  32113. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  32114. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  32115. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  32116. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  32117. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  32118. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  32119. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  32120. particleSystem.blendMode = parsedParticleSystem.blendMode;
  32121. if (!particleSystem.preventAutoStart) {
  32122. particleSystem.start();
  32123. }
  32124. return particleSystem;
  32125. };
  32126. return ParticleSystem;
  32127. }());
  32128. // Statics
  32129. ParticleSystem.BLENDMODE_ONEONE = 0;
  32130. ParticleSystem.BLENDMODE_STANDARD = 1;
  32131. BABYLON.ParticleSystem = ParticleSystem;
  32132. })(BABYLON || (BABYLON = {}));
  32133. //# sourceMappingURL=babylon.particleSystem.js.map
  32134. var BABYLON;
  32135. (function (BABYLON) {
  32136. var AnimationRange = (function () {
  32137. function AnimationRange(name, from, to) {
  32138. this.name = name;
  32139. this.from = from;
  32140. this.to = to;
  32141. }
  32142. AnimationRange.prototype.clone = function () {
  32143. return new AnimationRange(this.name, this.from, this.to);
  32144. };
  32145. return AnimationRange;
  32146. }());
  32147. BABYLON.AnimationRange = AnimationRange;
  32148. /**
  32149. * Composed of a frame, and an action function
  32150. */
  32151. var AnimationEvent = (function () {
  32152. function AnimationEvent(frame, action, onlyOnce) {
  32153. this.frame = frame;
  32154. this.action = action;
  32155. this.onlyOnce = onlyOnce;
  32156. this.isDone = false;
  32157. }
  32158. return AnimationEvent;
  32159. }());
  32160. BABYLON.AnimationEvent = AnimationEvent;
  32161. var PathCursor = (function () {
  32162. function PathCursor(path) {
  32163. this.path = path;
  32164. this._onchange = new Array();
  32165. this.value = 0;
  32166. this.animations = new Array();
  32167. }
  32168. PathCursor.prototype.getPoint = function () {
  32169. var point = this.path.getPointAtLengthPosition(this.value);
  32170. return new BABYLON.Vector3(point.x, 0, point.y);
  32171. };
  32172. PathCursor.prototype.moveAhead = function (step) {
  32173. if (step === void 0) { step = 0.002; }
  32174. this.move(step);
  32175. return this;
  32176. };
  32177. PathCursor.prototype.moveBack = function (step) {
  32178. if (step === void 0) { step = 0.002; }
  32179. this.move(-step);
  32180. return this;
  32181. };
  32182. PathCursor.prototype.move = function (step) {
  32183. if (Math.abs(step) > 1) {
  32184. throw "step size should be less than 1.";
  32185. }
  32186. this.value += step;
  32187. this.ensureLimits();
  32188. this.raiseOnChange();
  32189. return this;
  32190. };
  32191. PathCursor.prototype.ensureLimits = function () {
  32192. while (this.value > 1) {
  32193. this.value -= 1;
  32194. }
  32195. while (this.value < 0) {
  32196. this.value += 1;
  32197. }
  32198. return this;
  32199. };
  32200. // used by animation engine
  32201. PathCursor.prototype.markAsDirty = function (propertyName) {
  32202. this.ensureLimits();
  32203. this.raiseOnChange();
  32204. return this;
  32205. };
  32206. PathCursor.prototype.raiseOnChange = function () {
  32207. var _this = this;
  32208. this._onchange.forEach(function (f) { return f(_this); });
  32209. return this;
  32210. };
  32211. PathCursor.prototype.onchange = function (f) {
  32212. this._onchange.push(f);
  32213. return this;
  32214. };
  32215. return PathCursor;
  32216. }());
  32217. BABYLON.PathCursor = PathCursor;
  32218. var Animation = (function () {
  32219. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32220. this.name = name;
  32221. this.targetProperty = targetProperty;
  32222. this.framePerSecond = framePerSecond;
  32223. this.dataType = dataType;
  32224. this.loopMode = loopMode;
  32225. this.enableBlending = enableBlending;
  32226. this._offsetsCache = {};
  32227. this._highLimitsCache = {};
  32228. this._stopped = false;
  32229. this._blendingFactor = 0;
  32230. // The set of event that will be linked to this animation
  32231. this._events = new Array();
  32232. this.allowMatricesInterpolation = false;
  32233. this.blendingSpeed = 0.01;
  32234. this._ranges = {};
  32235. this.targetPropertyPath = targetProperty.split(".");
  32236. this.dataType = dataType;
  32237. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32238. }
  32239. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32240. var dataType = undefined;
  32241. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32242. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32243. }
  32244. else if (from instanceof BABYLON.Quaternion) {
  32245. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32246. }
  32247. else if (from instanceof BABYLON.Vector3) {
  32248. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32249. }
  32250. else if (from instanceof BABYLON.Vector2) {
  32251. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32252. }
  32253. else if (from instanceof BABYLON.Color3) {
  32254. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32255. }
  32256. else if (from instanceof BABYLON.Size) {
  32257. dataType = Animation.ANIMATIONTYPE_SIZE;
  32258. }
  32259. if (dataType == undefined) {
  32260. return null;
  32261. }
  32262. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32263. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32264. animation.setKeys(keys);
  32265. if (easingFunction !== undefined) {
  32266. animation.setEasingFunction(easingFunction);
  32267. }
  32268. return animation;
  32269. };
  32270. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32271. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32272. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32273. };
  32274. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32275. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32276. node.animations.push(animation);
  32277. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32278. };
  32279. // Methods
  32280. /**
  32281. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32282. */
  32283. Animation.prototype.toString = function (fullDetails) {
  32284. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32285. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32286. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32287. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32288. if (fullDetails) {
  32289. ret += ", Ranges: {";
  32290. var first = true;
  32291. for (var name in this._ranges) {
  32292. if (first) {
  32293. ret += ", ";
  32294. first = false;
  32295. }
  32296. ret += name;
  32297. }
  32298. ret += "}";
  32299. }
  32300. return ret;
  32301. };
  32302. /**
  32303. * Add an event to this animation.
  32304. */
  32305. Animation.prototype.addEvent = function (event) {
  32306. this._events.push(event);
  32307. };
  32308. /**
  32309. * Remove all events found at the given frame
  32310. * @param frame
  32311. */
  32312. Animation.prototype.removeEvents = function (frame) {
  32313. for (var index = 0; index < this._events.length; index++) {
  32314. if (this._events[index].frame === frame) {
  32315. this._events.splice(index, 1);
  32316. index--;
  32317. }
  32318. }
  32319. };
  32320. Animation.prototype.createRange = function (name, from, to) {
  32321. // check name not already in use; could happen for bones after serialized
  32322. if (!this._ranges[name]) {
  32323. this._ranges[name] = new AnimationRange(name, from, to);
  32324. }
  32325. };
  32326. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32327. if (deleteFrames === void 0) { deleteFrames = true; }
  32328. if (this._ranges[name]) {
  32329. if (deleteFrames) {
  32330. var from = this._ranges[name].from;
  32331. var to = this._ranges[name].to;
  32332. // this loop MUST go high to low for multiple splices to work
  32333. for (var key = this._keys.length - 1; key >= 0; key--) {
  32334. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32335. this._keys.splice(key, 1);
  32336. }
  32337. }
  32338. }
  32339. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32340. }
  32341. };
  32342. Animation.prototype.getRange = function (name) {
  32343. return this._ranges[name];
  32344. };
  32345. Animation.prototype.reset = function () {
  32346. this._offsetsCache = {};
  32347. this._highLimitsCache = {};
  32348. this.currentFrame = 0;
  32349. this._blendingFactor = 0;
  32350. this._originalBlendValue = null;
  32351. };
  32352. Animation.prototype.isStopped = function () {
  32353. return this._stopped;
  32354. };
  32355. Animation.prototype.getKeys = function () {
  32356. return this._keys;
  32357. };
  32358. Animation.prototype.getHighestFrame = function () {
  32359. var ret = 0;
  32360. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32361. if (ret < this._keys[key].frame) {
  32362. ret = this._keys[key].frame;
  32363. }
  32364. }
  32365. return ret;
  32366. };
  32367. Animation.prototype.getEasingFunction = function () {
  32368. return this._easingFunction;
  32369. };
  32370. Animation.prototype.setEasingFunction = function (easingFunction) {
  32371. this._easingFunction = easingFunction;
  32372. };
  32373. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32374. return startValue + (endValue - startValue) * gradient;
  32375. };
  32376. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32377. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32378. };
  32379. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32380. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32381. };
  32382. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32383. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32384. };
  32385. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32386. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32387. };
  32388. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32389. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32390. };
  32391. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32392. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32393. };
  32394. Animation.prototype.clone = function () {
  32395. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32396. clone.enableBlending = this.enableBlending;
  32397. clone.blendingSpeed = this.blendingSpeed;
  32398. if (this._keys) {
  32399. clone.setKeys(this._keys);
  32400. }
  32401. if (this._ranges) {
  32402. clone._ranges = {};
  32403. for (var name in this._ranges) {
  32404. clone._ranges[name] = this._ranges[name].clone();
  32405. }
  32406. }
  32407. return clone;
  32408. };
  32409. Animation.prototype.setKeys = function (values) {
  32410. this._keys = values.slice(0);
  32411. this._offsetsCache = {};
  32412. this._highLimitsCache = {};
  32413. };
  32414. Animation.prototype._getKeyValue = function (value) {
  32415. if (typeof value === "function") {
  32416. return value();
  32417. }
  32418. return value;
  32419. };
  32420. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32421. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32422. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32423. }
  32424. this.currentFrame = currentFrame;
  32425. // Try to get a hash to find the right key
  32426. 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));
  32427. if (this._keys[startKey].frame >= currentFrame) {
  32428. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32429. startKey--;
  32430. }
  32431. }
  32432. for (var key = startKey; key < this._keys.length; key++) {
  32433. if (this._keys[key + 1].frame >= currentFrame) {
  32434. var startValue = this._getKeyValue(this._keys[key].value);
  32435. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32436. // gradient : percent of currentFrame between the frame inf and the frame sup
  32437. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32438. // check for easingFunction and correction of gradient
  32439. if (this._easingFunction != null) {
  32440. gradient = this._easingFunction.ease(gradient);
  32441. }
  32442. switch (this.dataType) {
  32443. // Float
  32444. case Animation.ANIMATIONTYPE_FLOAT:
  32445. switch (loopMode) {
  32446. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32447. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32448. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32449. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32450. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32451. }
  32452. break;
  32453. // Quaternion
  32454. case Animation.ANIMATIONTYPE_QUATERNION:
  32455. var quaternion = null;
  32456. switch (loopMode) {
  32457. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32458. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32459. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32460. break;
  32461. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32462. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32463. break;
  32464. }
  32465. return quaternion;
  32466. // Vector3
  32467. case Animation.ANIMATIONTYPE_VECTOR3:
  32468. switch (loopMode) {
  32469. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32470. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32471. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32472. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32473. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32474. }
  32475. // Vector2
  32476. case Animation.ANIMATIONTYPE_VECTOR2:
  32477. switch (loopMode) {
  32478. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32479. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32480. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32481. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32482. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32483. }
  32484. // Size
  32485. case Animation.ANIMATIONTYPE_SIZE:
  32486. switch (loopMode) {
  32487. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32488. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32489. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32490. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32491. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32492. }
  32493. // Color3
  32494. case Animation.ANIMATIONTYPE_COLOR3:
  32495. switch (loopMode) {
  32496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32498. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32499. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32500. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32501. }
  32502. // Matrix
  32503. case Animation.ANIMATIONTYPE_MATRIX:
  32504. switch (loopMode) {
  32505. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32506. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32507. if (this.allowMatricesInterpolation) {
  32508. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32509. }
  32510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32511. return startValue;
  32512. }
  32513. default:
  32514. break;
  32515. }
  32516. break;
  32517. }
  32518. }
  32519. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32520. };
  32521. Animation.prototype.setValue = function (currentValue, blend) {
  32522. if (blend === void 0) { blend = false; }
  32523. // Set value
  32524. var path;
  32525. var destination;
  32526. if (this.targetPropertyPath.length > 1) {
  32527. var property = this._target[this.targetPropertyPath[0]];
  32528. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32529. property = property[this.targetPropertyPath[index]];
  32530. }
  32531. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32532. destination = property;
  32533. }
  32534. else {
  32535. path = this.targetPropertyPath[0];
  32536. destination = this._target;
  32537. }
  32538. // Blending
  32539. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32540. if (!this._originalBlendValue) {
  32541. if (destination[path].clone) {
  32542. this._originalBlendValue = destination[path].clone();
  32543. }
  32544. else {
  32545. this._originalBlendValue = destination[path];
  32546. }
  32547. }
  32548. if (this._originalBlendValue.prototype) {
  32549. if (this._originalBlendValue.prototype.Lerp) {
  32550. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32551. }
  32552. else {
  32553. destination[path] = currentValue;
  32554. }
  32555. }
  32556. else if (this._originalBlendValue.m) {
  32557. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32558. }
  32559. else {
  32560. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32561. }
  32562. this._blendingFactor += this.blendingSpeed;
  32563. }
  32564. else {
  32565. destination[path] = currentValue;
  32566. }
  32567. if (this._target.markAsDirty) {
  32568. this._target.markAsDirty(this.targetProperty);
  32569. }
  32570. };
  32571. Animation.prototype.goToFrame = function (frame) {
  32572. if (frame < this._keys[0].frame) {
  32573. frame = this._keys[0].frame;
  32574. }
  32575. else if (frame > this._keys[this._keys.length - 1].frame) {
  32576. frame = this._keys[this._keys.length - 1].frame;
  32577. }
  32578. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32579. this.setValue(currentValue);
  32580. };
  32581. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32582. if (blend === void 0) { blend = false; }
  32583. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32584. this._stopped = true;
  32585. return false;
  32586. }
  32587. var returnValue = true;
  32588. // Adding a start key at frame 0 if missing
  32589. if (this._keys[0].frame !== 0) {
  32590. var newKey = { frame: 0, value: this._keys[0].value };
  32591. this._keys.splice(0, 0, newKey);
  32592. }
  32593. // Check limits
  32594. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32595. from = this._keys[0].frame;
  32596. }
  32597. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32598. to = this._keys[this._keys.length - 1].frame;
  32599. }
  32600. //to and from cannot be the same key
  32601. if (from === to) {
  32602. from++;
  32603. }
  32604. // Compute ratio
  32605. var range = to - from;
  32606. var offsetValue;
  32607. // ratio represents the frame delta between from and to
  32608. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32609. var highLimitValue = 0;
  32610. if (ratio > range && !loop) {
  32611. returnValue = false;
  32612. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32613. }
  32614. else {
  32615. // Get max value if required
  32616. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32617. var keyOffset = to.toString() + from.toString();
  32618. if (!this._offsetsCache[keyOffset]) {
  32619. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32620. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32621. switch (this.dataType) {
  32622. // Float
  32623. case Animation.ANIMATIONTYPE_FLOAT:
  32624. this._offsetsCache[keyOffset] = toValue - fromValue;
  32625. break;
  32626. // Quaternion
  32627. case Animation.ANIMATIONTYPE_QUATERNION:
  32628. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32629. break;
  32630. // Vector3
  32631. case Animation.ANIMATIONTYPE_VECTOR3:
  32632. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32633. // Vector2
  32634. case Animation.ANIMATIONTYPE_VECTOR2:
  32635. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32636. // Size
  32637. case Animation.ANIMATIONTYPE_SIZE:
  32638. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32639. // Color3
  32640. case Animation.ANIMATIONTYPE_COLOR3:
  32641. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32642. default:
  32643. break;
  32644. }
  32645. this._highLimitsCache[keyOffset] = toValue;
  32646. }
  32647. highLimitValue = this._highLimitsCache[keyOffset];
  32648. offsetValue = this._offsetsCache[keyOffset];
  32649. }
  32650. }
  32651. if (offsetValue === undefined) {
  32652. switch (this.dataType) {
  32653. // Float
  32654. case Animation.ANIMATIONTYPE_FLOAT:
  32655. offsetValue = 0;
  32656. break;
  32657. // Quaternion
  32658. case Animation.ANIMATIONTYPE_QUATERNION:
  32659. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32660. break;
  32661. // Vector3
  32662. case Animation.ANIMATIONTYPE_VECTOR3:
  32663. offsetValue = BABYLON.Vector3.Zero();
  32664. break;
  32665. // Vector2
  32666. case Animation.ANIMATIONTYPE_VECTOR2:
  32667. offsetValue = BABYLON.Vector2.Zero();
  32668. break;
  32669. // Size
  32670. case Animation.ANIMATIONTYPE_SIZE:
  32671. offsetValue = BABYLON.Size.Zero();
  32672. break;
  32673. // Color3
  32674. case Animation.ANIMATIONTYPE_COLOR3:
  32675. offsetValue = BABYLON.Color3.Black();
  32676. }
  32677. }
  32678. // Compute value
  32679. var repeatCount = (ratio / range) >> 0;
  32680. var currentFrame = returnValue ? from + ratio % range : to;
  32681. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32682. // Set value
  32683. this.setValue(currentValue);
  32684. // Check events
  32685. for (var index = 0; index < this._events.length; index++) {
  32686. if (currentFrame >= this._events[index].frame) {
  32687. var event = this._events[index];
  32688. if (!event.isDone) {
  32689. // If event should be done only once, remove it.
  32690. if (event.onlyOnce) {
  32691. this._events.splice(index, 1);
  32692. index--;
  32693. }
  32694. event.isDone = true;
  32695. event.action();
  32696. } // Don't do anything if the event has already be done.
  32697. }
  32698. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32699. // reset event, the animation is looping
  32700. this._events[index].isDone = false;
  32701. }
  32702. }
  32703. if (!returnValue) {
  32704. this._stopped = true;
  32705. }
  32706. return returnValue;
  32707. };
  32708. Animation.prototype.serialize = function () {
  32709. var serializationObject = {};
  32710. serializationObject.name = this.name;
  32711. serializationObject.property = this.targetProperty;
  32712. serializationObject.framePerSecond = this.framePerSecond;
  32713. serializationObject.dataType = this.dataType;
  32714. serializationObject.loopBehavior = this.loopMode;
  32715. serializationObject.enableBlending = this.enableBlending;
  32716. serializationObject.blendingSpeed = this.blendingSpeed;
  32717. var dataType = this.dataType;
  32718. serializationObject.keys = [];
  32719. var keys = this.getKeys();
  32720. for (var index = 0; index < keys.length; index++) {
  32721. var animationKey = keys[index];
  32722. var key = {};
  32723. key.frame = animationKey.frame;
  32724. switch (dataType) {
  32725. case Animation.ANIMATIONTYPE_FLOAT:
  32726. key.values = [animationKey.value];
  32727. break;
  32728. case Animation.ANIMATIONTYPE_QUATERNION:
  32729. case Animation.ANIMATIONTYPE_MATRIX:
  32730. case Animation.ANIMATIONTYPE_VECTOR3:
  32731. case Animation.ANIMATIONTYPE_COLOR3:
  32732. key.values = animationKey.value.asArray();
  32733. break;
  32734. }
  32735. serializationObject.keys.push(key);
  32736. }
  32737. serializationObject.ranges = [];
  32738. for (var name in this._ranges) {
  32739. var range = {};
  32740. range.name = name;
  32741. range.from = this._ranges[name].from;
  32742. range.to = this._ranges[name].to;
  32743. serializationObject.ranges.push(range);
  32744. }
  32745. return serializationObject;
  32746. };
  32747. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32748. get: function () {
  32749. return Animation._ANIMATIONTYPE_FLOAT;
  32750. },
  32751. enumerable: true,
  32752. configurable: true
  32753. });
  32754. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32755. get: function () {
  32756. return Animation._ANIMATIONTYPE_VECTOR3;
  32757. },
  32758. enumerable: true,
  32759. configurable: true
  32760. });
  32761. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32762. get: function () {
  32763. return Animation._ANIMATIONTYPE_VECTOR2;
  32764. },
  32765. enumerable: true,
  32766. configurable: true
  32767. });
  32768. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32769. get: function () {
  32770. return Animation._ANIMATIONTYPE_SIZE;
  32771. },
  32772. enumerable: true,
  32773. configurable: true
  32774. });
  32775. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32776. get: function () {
  32777. return Animation._ANIMATIONTYPE_QUATERNION;
  32778. },
  32779. enumerable: true,
  32780. configurable: true
  32781. });
  32782. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32783. get: function () {
  32784. return Animation._ANIMATIONTYPE_MATRIX;
  32785. },
  32786. enumerable: true,
  32787. configurable: true
  32788. });
  32789. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32790. get: function () {
  32791. return Animation._ANIMATIONTYPE_COLOR3;
  32792. },
  32793. enumerable: true,
  32794. configurable: true
  32795. });
  32796. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32797. get: function () {
  32798. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32799. },
  32800. enumerable: true,
  32801. configurable: true
  32802. });
  32803. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32804. get: function () {
  32805. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32806. },
  32807. enumerable: true,
  32808. configurable: true
  32809. });
  32810. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32811. get: function () {
  32812. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32813. },
  32814. enumerable: true,
  32815. configurable: true
  32816. });
  32817. Animation.Parse = function (parsedAnimation) {
  32818. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32819. var dataType = parsedAnimation.dataType;
  32820. var keys = [];
  32821. var data;
  32822. var index;
  32823. if (parsedAnimation.enableBlending) {
  32824. animation.enableBlending = parsedAnimation.enableBlending;
  32825. }
  32826. if (parsedAnimation.blendingSpeed) {
  32827. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32828. }
  32829. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32830. var key = parsedAnimation.keys[index];
  32831. switch (dataType) {
  32832. case Animation.ANIMATIONTYPE_FLOAT:
  32833. data = key.values[0];
  32834. break;
  32835. case Animation.ANIMATIONTYPE_QUATERNION:
  32836. data = BABYLON.Quaternion.FromArray(key.values);
  32837. break;
  32838. case Animation.ANIMATIONTYPE_MATRIX:
  32839. data = BABYLON.Matrix.FromArray(key.values);
  32840. break;
  32841. case Animation.ANIMATIONTYPE_COLOR3:
  32842. data = BABYLON.Color3.FromArray(key.values);
  32843. break;
  32844. case Animation.ANIMATIONTYPE_VECTOR3:
  32845. default:
  32846. data = BABYLON.Vector3.FromArray(key.values);
  32847. break;
  32848. }
  32849. keys.push({
  32850. frame: key.frame,
  32851. value: data
  32852. });
  32853. }
  32854. animation.setKeys(keys);
  32855. if (parsedAnimation.ranges) {
  32856. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32857. data = parsedAnimation.ranges[index];
  32858. animation.createRange(data.name, data.from, data.to);
  32859. }
  32860. }
  32861. return animation;
  32862. };
  32863. Animation.AppendSerializedAnimations = function (source, destination) {
  32864. if (source.animations) {
  32865. destination.animations = [];
  32866. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32867. var animation = source.animations[animationIndex];
  32868. destination.animations.push(animation.serialize());
  32869. }
  32870. }
  32871. };
  32872. return Animation;
  32873. }());
  32874. // Statics
  32875. Animation._ANIMATIONTYPE_FLOAT = 0;
  32876. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32877. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32878. Animation._ANIMATIONTYPE_MATRIX = 3;
  32879. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32880. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32881. Animation._ANIMATIONTYPE_SIZE = 6;
  32882. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32883. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32884. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32885. BABYLON.Animation = Animation;
  32886. })(BABYLON || (BABYLON = {}));
  32887. //# sourceMappingURL=babylon.animation.js.map
  32888. var BABYLON;
  32889. (function (BABYLON) {
  32890. var Animatable = (function () {
  32891. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32892. if (fromFrame === void 0) { fromFrame = 0; }
  32893. if (toFrame === void 0) { toFrame = 100; }
  32894. if (loopAnimation === void 0) { loopAnimation = false; }
  32895. if (speedRatio === void 0) { speedRatio = 1.0; }
  32896. this.target = target;
  32897. this.fromFrame = fromFrame;
  32898. this.toFrame = toFrame;
  32899. this.loopAnimation = loopAnimation;
  32900. this.speedRatio = speedRatio;
  32901. this.onAnimationEnd = onAnimationEnd;
  32902. this._animations = new Array();
  32903. this._paused = false;
  32904. this.animationStarted = false;
  32905. if (animations) {
  32906. this.appendAnimations(target, animations);
  32907. }
  32908. this._scene = scene;
  32909. scene._activeAnimatables.push(this);
  32910. }
  32911. // Methods
  32912. Animatable.prototype.getAnimations = function () {
  32913. return this._animations;
  32914. };
  32915. Animatable.prototype.appendAnimations = function (target, animations) {
  32916. for (var index = 0; index < animations.length; index++) {
  32917. var animation = animations[index];
  32918. animation._target = target;
  32919. this._animations.push(animation);
  32920. }
  32921. };
  32922. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32923. var animations = this._animations;
  32924. for (var index = 0; index < animations.length; index++) {
  32925. if (animations[index].targetProperty === property) {
  32926. return animations[index];
  32927. }
  32928. }
  32929. return null;
  32930. };
  32931. Animatable.prototype.reset = function () {
  32932. var animations = this._animations;
  32933. for (var index = 0; index < animations.length; index++) {
  32934. animations[index].reset();
  32935. }
  32936. this._localDelayOffset = null;
  32937. this._pausedDelay = null;
  32938. };
  32939. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32940. var animations = this._animations;
  32941. for (var index = 0; index < animations.length; index++) {
  32942. animations[index].enableBlending = true;
  32943. animations[index].blendingSpeed = blendingSpeed;
  32944. }
  32945. };
  32946. Animatable.prototype.disableBlending = function () {
  32947. var animations = this._animations;
  32948. for (var index = 0; index < animations.length; index++) {
  32949. animations[index].enableBlending = false;
  32950. }
  32951. };
  32952. Animatable.prototype.goToFrame = function (frame) {
  32953. var animations = this._animations;
  32954. if (animations[0]) {
  32955. var fps = animations[0].framePerSecond;
  32956. var currentFrame = animations[0].currentFrame;
  32957. var adjustTime = frame - currentFrame;
  32958. var delay = adjustTime * 1000 / fps;
  32959. this._localDelayOffset -= delay;
  32960. }
  32961. for (var index = 0; index < animations.length; index++) {
  32962. animations[index].goToFrame(frame);
  32963. }
  32964. };
  32965. Animatable.prototype.pause = function () {
  32966. if (this._paused) {
  32967. return;
  32968. }
  32969. this._paused = true;
  32970. };
  32971. Animatable.prototype.restart = function () {
  32972. this._paused = false;
  32973. };
  32974. Animatable.prototype.stop = function (animationName) {
  32975. if (animationName) {
  32976. var idx = this._scene._activeAnimatables.indexOf(this);
  32977. if (idx > -1) {
  32978. var animations = this._animations;
  32979. for (var index = animations.length - 1; index >= 0; index--) {
  32980. if (typeof animationName === "string" && animations[index].name != animationName) {
  32981. continue;
  32982. }
  32983. animations[index].reset();
  32984. animations.splice(index, 1);
  32985. }
  32986. if (animations.length == 0) {
  32987. this._scene._activeAnimatables.splice(idx, 1);
  32988. if (this.onAnimationEnd) {
  32989. this.onAnimationEnd();
  32990. }
  32991. }
  32992. }
  32993. }
  32994. else {
  32995. var index = this._scene._activeAnimatables.indexOf(this);
  32996. if (index > -1) {
  32997. this._scene._activeAnimatables.splice(index, 1);
  32998. var animations = this._animations;
  32999. for (var index = 0; index < animations.length; index++) {
  33000. animations[index].reset();
  33001. }
  33002. if (this.onAnimationEnd) {
  33003. this.onAnimationEnd();
  33004. }
  33005. }
  33006. }
  33007. };
  33008. Animatable.prototype._animate = function (delay) {
  33009. if (this._paused) {
  33010. this.animationStarted = false;
  33011. if (!this._pausedDelay) {
  33012. this._pausedDelay = delay;
  33013. }
  33014. return true;
  33015. }
  33016. if (!this._localDelayOffset) {
  33017. this._localDelayOffset = delay;
  33018. }
  33019. else if (this._pausedDelay) {
  33020. this._localDelayOffset += delay - this._pausedDelay;
  33021. this._pausedDelay = null;
  33022. }
  33023. // Animating
  33024. var running = false;
  33025. var animations = this._animations;
  33026. var index;
  33027. for (index = 0; index < animations.length; index++) {
  33028. var animation = animations[index];
  33029. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33030. running = running || isRunning;
  33031. }
  33032. this.animationStarted = running;
  33033. if (!running) {
  33034. // Remove from active animatables
  33035. index = this._scene._activeAnimatables.indexOf(this);
  33036. this._scene._activeAnimatables.splice(index, 1);
  33037. }
  33038. if (!running && this.onAnimationEnd) {
  33039. this.onAnimationEnd();
  33040. this.onAnimationEnd = null;
  33041. }
  33042. return running;
  33043. };
  33044. return Animatable;
  33045. }());
  33046. BABYLON.Animatable = Animatable;
  33047. })(BABYLON || (BABYLON = {}));
  33048. //# sourceMappingURL=babylon.animatable.js.map
  33049. var BABYLON;
  33050. (function (BABYLON) {
  33051. var EasingFunction = (function () {
  33052. function EasingFunction() {
  33053. // Properties
  33054. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33055. }
  33056. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33057. get: function () {
  33058. return EasingFunction._EASINGMODE_EASEIN;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33064. get: function () {
  33065. return EasingFunction._EASINGMODE_EASEOUT;
  33066. },
  33067. enumerable: true,
  33068. configurable: true
  33069. });
  33070. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33071. get: function () {
  33072. return EasingFunction._EASINGMODE_EASEINOUT;
  33073. },
  33074. enumerable: true,
  33075. configurable: true
  33076. });
  33077. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33078. var n = Math.min(Math.max(easingMode, 0), 2);
  33079. this._easingMode = n;
  33080. };
  33081. EasingFunction.prototype.getEasingMode = function () {
  33082. return this._easingMode;
  33083. };
  33084. EasingFunction.prototype.easeInCore = function (gradient) {
  33085. throw new Error('You must implement this method');
  33086. };
  33087. EasingFunction.prototype.ease = function (gradient) {
  33088. switch (this._easingMode) {
  33089. case EasingFunction.EASINGMODE_EASEIN:
  33090. return this.easeInCore(gradient);
  33091. case EasingFunction.EASINGMODE_EASEOUT:
  33092. return (1 - this.easeInCore(1 - gradient));
  33093. }
  33094. if (gradient >= 0.5) {
  33095. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33096. }
  33097. return (this.easeInCore(gradient * 2) * 0.5);
  33098. };
  33099. return EasingFunction;
  33100. }());
  33101. //Statics
  33102. EasingFunction._EASINGMODE_EASEIN = 0;
  33103. EasingFunction._EASINGMODE_EASEOUT = 1;
  33104. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33105. BABYLON.EasingFunction = EasingFunction;
  33106. var CircleEase = (function (_super) {
  33107. __extends(CircleEase, _super);
  33108. function CircleEase() {
  33109. return _super.apply(this, arguments) || this;
  33110. }
  33111. CircleEase.prototype.easeInCore = function (gradient) {
  33112. gradient = Math.max(0, Math.min(1, gradient));
  33113. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33114. };
  33115. return CircleEase;
  33116. }(EasingFunction));
  33117. BABYLON.CircleEase = CircleEase;
  33118. var BackEase = (function (_super) {
  33119. __extends(BackEase, _super);
  33120. function BackEase(amplitude) {
  33121. if (amplitude === void 0) { amplitude = 1; }
  33122. var _this = _super.call(this) || this;
  33123. _this.amplitude = amplitude;
  33124. return _this;
  33125. }
  33126. BackEase.prototype.easeInCore = function (gradient) {
  33127. var num = Math.max(0, this.amplitude);
  33128. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33129. };
  33130. return BackEase;
  33131. }(EasingFunction));
  33132. BABYLON.BackEase = BackEase;
  33133. var BounceEase = (function (_super) {
  33134. __extends(BounceEase, _super);
  33135. function BounceEase(bounces, bounciness) {
  33136. if (bounces === void 0) { bounces = 3; }
  33137. if (bounciness === void 0) { bounciness = 2; }
  33138. var _this = _super.call(this) || this;
  33139. _this.bounces = bounces;
  33140. _this.bounciness = bounciness;
  33141. return _this;
  33142. }
  33143. BounceEase.prototype.easeInCore = function (gradient) {
  33144. var y = Math.max(0.0, this.bounces);
  33145. var bounciness = this.bounciness;
  33146. if (bounciness <= 1.0) {
  33147. bounciness = 1.001;
  33148. }
  33149. var num9 = Math.pow(bounciness, y);
  33150. var num5 = 1.0 - bounciness;
  33151. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33152. var num15 = gradient * num4;
  33153. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33154. var num3 = Math.floor(num65);
  33155. var num13 = num3 + 1.0;
  33156. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33157. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33158. var num7 = (num8 + num12) * 0.5;
  33159. var num6 = gradient - num7;
  33160. var num2 = num7 - num8;
  33161. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33162. };
  33163. return BounceEase;
  33164. }(EasingFunction));
  33165. BABYLON.BounceEase = BounceEase;
  33166. var CubicEase = (function (_super) {
  33167. __extends(CubicEase, _super);
  33168. function CubicEase() {
  33169. return _super.apply(this, arguments) || this;
  33170. }
  33171. CubicEase.prototype.easeInCore = function (gradient) {
  33172. return (gradient * gradient * gradient);
  33173. };
  33174. return CubicEase;
  33175. }(EasingFunction));
  33176. BABYLON.CubicEase = CubicEase;
  33177. var ElasticEase = (function (_super) {
  33178. __extends(ElasticEase, _super);
  33179. function ElasticEase(oscillations, springiness) {
  33180. if (oscillations === void 0) { oscillations = 3; }
  33181. if (springiness === void 0) { springiness = 3; }
  33182. var _this = _super.call(this) || this;
  33183. _this.oscillations = oscillations;
  33184. _this.springiness = springiness;
  33185. return _this;
  33186. }
  33187. ElasticEase.prototype.easeInCore = function (gradient) {
  33188. var num2;
  33189. var num3 = Math.max(0.0, this.oscillations);
  33190. var num = Math.max(0.0, this.springiness);
  33191. if (num == 0) {
  33192. num2 = gradient;
  33193. }
  33194. else {
  33195. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33196. }
  33197. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33198. };
  33199. return ElasticEase;
  33200. }(EasingFunction));
  33201. BABYLON.ElasticEase = ElasticEase;
  33202. var ExponentialEase = (function (_super) {
  33203. __extends(ExponentialEase, _super);
  33204. function ExponentialEase(exponent) {
  33205. if (exponent === void 0) { exponent = 2; }
  33206. var _this = _super.call(this) || this;
  33207. _this.exponent = exponent;
  33208. return _this;
  33209. }
  33210. ExponentialEase.prototype.easeInCore = function (gradient) {
  33211. if (this.exponent <= 0) {
  33212. return gradient;
  33213. }
  33214. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33215. };
  33216. return ExponentialEase;
  33217. }(EasingFunction));
  33218. BABYLON.ExponentialEase = ExponentialEase;
  33219. var PowerEase = (function (_super) {
  33220. __extends(PowerEase, _super);
  33221. function PowerEase(power) {
  33222. if (power === void 0) { power = 2; }
  33223. var _this = _super.call(this) || this;
  33224. _this.power = power;
  33225. return _this;
  33226. }
  33227. PowerEase.prototype.easeInCore = function (gradient) {
  33228. var y = Math.max(0.0, this.power);
  33229. return Math.pow(gradient, y);
  33230. };
  33231. return PowerEase;
  33232. }(EasingFunction));
  33233. BABYLON.PowerEase = PowerEase;
  33234. var QuadraticEase = (function (_super) {
  33235. __extends(QuadraticEase, _super);
  33236. function QuadraticEase() {
  33237. return _super.apply(this, arguments) || this;
  33238. }
  33239. QuadraticEase.prototype.easeInCore = function (gradient) {
  33240. return (gradient * gradient);
  33241. };
  33242. return QuadraticEase;
  33243. }(EasingFunction));
  33244. BABYLON.QuadraticEase = QuadraticEase;
  33245. var QuarticEase = (function (_super) {
  33246. __extends(QuarticEase, _super);
  33247. function QuarticEase() {
  33248. return _super.apply(this, arguments) || this;
  33249. }
  33250. QuarticEase.prototype.easeInCore = function (gradient) {
  33251. return (gradient * gradient * gradient * gradient);
  33252. };
  33253. return QuarticEase;
  33254. }(EasingFunction));
  33255. BABYLON.QuarticEase = QuarticEase;
  33256. var QuinticEase = (function (_super) {
  33257. __extends(QuinticEase, _super);
  33258. function QuinticEase() {
  33259. return _super.apply(this, arguments) || this;
  33260. }
  33261. QuinticEase.prototype.easeInCore = function (gradient) {
  33262. return (gradient * gradient * gradient * gradient * gradient);
  33263. };
  33264. return QuinticEase;
  33265. }(EasingFunction));
  33266. BABYLON.QuinticEase = QuinticEase;
  33267. var SineEase = (function (_super) {
  33268. __extends(SineEase, _super);
  33269. function SineEase() {
  33270. return _super.apply(this, arguments) || this;
  33271. }
  33272. SineEase.prototype.easeInCore = function (gradient) {
  33273. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33274. };
  33275. return SineEase;
  33276. }(EasingFunction));
  33277. BABYLON.SineEase = SineEase;
  33278. var BezierCurveEase = (function (_super) {
  33279. __extends(BezierCurveEase, _super);
  33280. function BezierCurveEase(x1, y1, x2, y2) {
  33281. if (x1 === void 0) { x1 = 0; }
  33282. if (y1 === void 0) { y1 = 0; }
  33283. if (x2 === void 0) { x2 = 1; }
  33284. if (y2 === void 0) { y2 = 1; }
  33285. var _this = _super.call(this) || this;
  33286. _this.x1 = x1;
  33287. _this.y1 = y1;
  33288. _this.x2 = x2;
  33289. _this.y2 = y2;
  33290. return _this;
  33291. }
  33292. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33293. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33294. };
  33295. return BezierCurveEase;
  33296. }(EasingFunction));
  33297. BABYLON.BezierCurveEase = BezierCurveEase;
  33298. })(BABYLON || (BABYLON = {}));
  33299. //# sourceMappingURL=babylon.easing.js.map
  33300. /// <reference path="..\babylon.node.ts" />
  33301. var BABYLON;
  33302. (function (BABYLON) {
  33303. var Bone = (function (_super) {
  33304. __extends(Bone, _super);
  33305. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33306. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33307. _this.name = name;
  33308. _this.children = new Array();
  33309. _this.animations = new Array();
  33310. _this._worldTransform = new BABYLON.Matrix();
  33311. _this._absoluteTransform = new BABYLON.Matrix();
  33312. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33313. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33314. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33315. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33316. _this._scalingDeterminant = 1;
  33317. _this._skeleton = skeleton;
  33318. _this._localMatrix = matrix;
  33319. _this._baseMatrix = matrix.clone();
  33320. _this._restPose = restPose ? restPose : matrix.clone();
  33321. skeleton.bones.push(_this);
  33322. if (parentBone) {
  33323. _this._parent = parentBone;
  33324. parentBone.children.push(_this);
  33325. }
  33326. else {
  33327. _this._parent = null;
  33328. }
  33329. _this._updateDifferenceMatrix();
  33330. if (_this.getAbsoluteTransform().determinant() < 0) {
  33331. _this._scalingDeterminant *= -1;
  33332. }
  33333. return _this;
  33334. }
  33335. Object.defineProperty(Bone.prototype, "_matrix", {
  33336. get: function () {
  33337. return this._localMatrix;
  33338. },
  33339. set: function (val) {
  33340. if (this._localMatrix) {
  33341. this._localMatrix.copyFrom(val);
  33342. }
  33343. else {
  33344. this._localMatrix = val;
  33345. }
  33346. },
  33347. enumerable: true,
  33348. configurable: true
  33349. });
  33350. // Members
  33351. Bone.prototype.getParent = function () {
  33352. return this._parent;
  33353. };
  33354. Bone.prototype.getLocalMatrix = function () {
  33355. return this._localMatrix;
  33356. };
  33357. Bone.prototype.getBaseMatrix = function () {
  33358. return this._baseMatrix;
  33359. };
  33360. Bone.prototype.getRestPose = function () {
  33361. return this._restPose;
  33362. };
  33363. Bone.prototype.returnToRest = function () {
  33364. this.updateMatrix(this._restPose.clone());
  33365. };
  33366. Bone.prototype.getWorldMatrix = function () {
  33367. return this._worldTransform;
  33368. };
  33369. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33370. return this._invertedAbsoluteTransform;
  33371. };
  33372. Bone.prototype.getAbsoluteTransform = function () {
  33373. return this._absoluteTransform;
  33374. };
  33375. // Methods
  33376. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33377. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33378. this._baseMatrix = matrix.clone();
  33379. this._localMatrix = matrix.clone();
  33380. this._skeleton._markAsDirty();
  33381. if (updateDifferenceMatrix) {
  33382. this._updateDifferenceMatrix();
  33383. }
  33384. };
  33385. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33386. if (!rootMatrix) {
  33387. rootMatrix = this._baseMatrix;
  33388. }
  33389. if (this._parent) {
  33390. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33391. }
  33392. else {
  33393. this._absoluteTransform.copyFrom(rootMatrix);
  33394. }
  33395. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33396. for (var index = 0; index < this.children.length; index++) {
  33397. this.children[index]._updateDifferenceMatrix();
  33398. }
  33399. };
  33400. Bone.prototype.markAsDirty = function () {
  33401. this._currentRenderId++;
  33402. this._skeleton._markAsDirty();
  33403. };
  33404. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33405. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33406. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33407. // all animation may be coming from a library skeleton, so may need to create animation
  33408. if (this.animations.length === 0) {
  33409. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33410. this.animations[0].setKeys([]);
  33411. }
  33412. // get animation info / verify there is such a range from the source bone
  33413. var sourceRange = source.animations[0].getRange(rangeName);
  33414. if (!sourceRange) {
  33415. return false;
  33416. }
  33417. var from = sourceRange.from;
  33418. var to = sourceRange.to;
  33419. var sourceKeys = source.animations[0].getKeys();
  33420. // rescaling prep
  33421. var sourceBoneLength = source.length;
  33422. var sourceParent = source.getParent();
  33423. var parent = this.getParent();
  33424. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  33425. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  33426. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  33427. var destKeys = this.animations[0].getKeys();
  33428. // loop vars declaration
  33429. var orig;
  33430. var origTranslation;
  33431. var mat;
  33432. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  33433. orig = sourceKeys[key];
  33434. if (orig.frame >= from && orig.frame <= to) {
  33435. if (rescaleAsRequired) {
  33436. mat = orig.value.clone();
  33437. // scale based on parent ratio, when bone has parent
  33438. if (parentScalingReqd) {
  33439. origTranslation = mat.getTranslation();
  33440. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  33441. }
  33442. else if (dimensionsScalingReqd) {
  33443. origTranslation = mat.getTranslation();
  33444. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  33445. }
  33446. else {
  33447. mat = orig.value;
  33448. }
  33449. }
  33450. else {
  33451. mat = orig.value;
  33452. }
  33453. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  33454. }
  33455. }
  33456. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  33457. return true;
  33458. };
  33459. /**
  33460. * Translate the bone in local or world space.
  33461. * @param vec The amount to translate the bone.
  33462. * @param space The space that the translation is in.
  33463. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33464. */
  33465. Bone.prototype.translate = function (vec, space, mesh) {
  33466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33467. var lm = this.getLocalMatrix();
  33468. if (space == BABYLON.Space.LOCAL) {
  33469. lm.m[12] += vec.x;
  33470. lm.m[13] += vec.y;
  33471. lm.m[14] += vec.z;
  33472. }
  33473. else {
  33474. var wm;
  33475. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33476. if (mesh) {
  33477. wm = mesh.getWorldMatrix();
  33478. }
  33479. this._skeleton.computeAbsoluteTransforms();
  33480. var tmat = BABYLON.Tmp.Matrix[0];
  33481. var tvec = BABYLON.Tmp.Vector3[0];
  33482. if (mesh) {
  33483. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33484. tmat.multiplyToRef(wm, tmat);
  33485. }
  33486. else {
  33487. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33488. }
  33489. tmat.m[12] = 0;
  33490. tmat.m[13] = 0;
  33491. tmat.m[14] = 0;
  33492. tmat.invert();
  33493. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  33494. lm.m[12] += tvec.x;
  33495. lm.m[13] += tvec.y;
  33496. lm.m[14] += tvec.z;
  33497. }
  33498. this.markAsDirty();
  33499. };
  33500. /**
  33501. * Set the postion of the bone in local or world space.
  33502. * @param position The position to set the bone.
  33503. * @param space The space that the position is in.
  33504. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33505. */
  33506. Bone.prototype.setPosition = function (position, space, mesh) {
  33507. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33508. var lm = this.getLocalMatrix();
  33509. if (space == BABYLON.Space.LOCAL) {
  33510. lm.m[12] = position.x;
  33511. lm.m[13] = position.y;
  33512. lm.m[14] = position.z;
  33513. }
  33514. else {
  33515. var wm;
  33516. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33517. if (mesh) {
  33518. wm = mesh.getWorldMatrix();
  33519. }
  33520. this._skeleton.computeAbsoluteTransforms();
  33521. var tmat = BABYLON.Tmp.Matrix[0];
  33522. var vec = BABYLON.Tmp.Vector3[0];
  33523. if (mesh) {
  33524. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33525. tmat.multiplyToRef(wm, tmat);
  33526. }
  33527. else {
  33528. tmat.copyFrom(this._parent.getAbsoluteTransform());
  33529. }
  33530. tmat.invert();
  33531. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  33532. lm.m[12] = vec.x;
  33533. lm.m[13] = vec.y;
  33534. lm.m[14] = vec.z;
  33535. }
  33536. this.markAsDirty();
  33537. };
  33538. /**
  33539. * Set the absolute postion of the bone (world space).
  33540. * @param position The position to set the bone.
  33541. * @param mesh The mesh that this bone is attached to.
  33542. */
  33543. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  33544. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  33545. };
  33546. /**
  33547. * Set the scale of the bone on the x, y and z axes.
  33548. * @param x The scale of the bone on the x axis.
  33549. * @param x The scale of the bone on the y axis.
  33550. * @param z The scale of the bone on the z axis.
  33551. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33552. */
  33553. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  33554. if (scaleChildren === void 0) { scaleChildren = false; }
  33555. if (this.animations[0] && !this.animations[0].isStopped()) {
  33556. if (!scaleChildren) {
  33557. this._negateScaleChildren.x = 1 / x;
  33558. this._negateScaleChildren.y = 1 / y;
  33559. this._negateScaleChildren.z = 1 / z;
  33560. }
  33561. this._syncScaleVector();
  33562. }
  33563. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  33564. };
  33565. /**
  33566. * Scale the bone on the x, y and z axes.
  33567. * @param x The amount to scale the bone on the x axis.
  33568. * @param x The amount to scale the bone on the y axis.
  33569. * @param z The amount to scale the bone on the z axis.
  33570. * @param scaleChildren Set this to true if children of the bone should be scaled.
  33571. */
  33572. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  33573. if (scaleChildren === void 0) { scaleChildren = false; }
  33574. var locMat = this.getLocalMatrix();
  33575. var origLocMat = BABYLON.Tmp.Matrix[0];
  33576. origLocMat.copyFrom(locMat);
  33577. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  33578. origLocMatInv.copyFrom(origLocMat);
  33579. origLocMatInv.invert();
  33580. var scaleMat = BABYLON.Tmp.Matrix[2];
  33581. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  33582. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  33583. this._scaleVector.x *= x;
  33584. this._scaleVector.y *= y;
  33585. this._scaleVector.z *= z;
  33586. locMat.multiplyToRef(origLocMatInv, locMat);
  33587. locMat.multiplyToRef(scaleMat, locMat);
  33588. locMat.multiplyToRef(origLocMat, locMat);
  33589. var parent = this.getParent();
  33590. if (parent) {
  33591. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  33592. }
  33593. else {
  33594. this.getAbsoluteTransform().copyFrom(locMat);
  33595. }
  33596. var len = this.children.length;
  33597. scaleMat.invert();
  33598. for (var i = 0; i < len; i++) {
  33599. var child = this.children[i];
  33600. var cm = child.getLocalMatrix();
  33601. cm.multiplyToRef(scaleMat, cm);
  33602. var lm = child.getLocalMatrix();
  33603. lm.m[12] *= x;
  33604. lm.m[13] *= y;
  33605. lm.m[14] *= z;
  33606. }
  33607. this.computeAbsoluteTransforms();
  33608. if (scaleChildren) {
  33609. for (var i = 0; i < len; i++) {
  33610. this.children[i].scale(x, y, z, scaleChildren);
  33611. }
  33612. }
  33613. this.markAsDirty();
  33614. };
  33615. /**
  33616. * Set the yaw, pitch, and roll of the bone in local or world space.
  33617. * @param yaw The rotation of the bone on the y axis.
  33618. * @param pitch The rotation of the bone on the x axis.
  33619. * @param roll The rotation of the bone on the z axis.
  33620. * @param space The space that the axes of rotation are in.
  33621. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33622. */
  33623. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  33624. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33625. var rotMat = BABYLON.Tmp.Matrix[0];
  33626. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  33627. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33628. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33629. rotMatInv.multiplyToRef(rotMat, rotMat);
  33630. this._rotateWithMatrix(rotMat, space, mesh);
  33631. };
  33632. /**
  33633. * Rotate the bone on an axis in local or world space.
  33634. * @param axis The axis to rotate the bone on.
  33635. * @param amount The amount to rotate the bone.
  33636. * @param space The space that the axis is in.
  33637. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33638. */
  33639. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  33640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33641. var rmat = BABYLON.Tmp.Matrix[0];
  33642. rmat.m[12] = 0;
  33643. rmat.m[13] = 0;
  33644. rmat.m[14] = 0;
  33645. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  33646. this._rotateWithMatrix(rmat, space, mesh);
  33647. };
  33648. /**
  33649. * Set the rotation of the bone to a particular axis angle in local or world space.
  33650. * @param axis The axis to rotate the bone on.
  33651. * @param angle The angle that the bone should be rotated to.
  33652. * @param space The space that the axis is in.
  33653. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33654. */
  33655. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  33656. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33657. var rotMat = BABYLON.Tmp.Matrix[0];
  33658. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  33659. var rotMatInv = BABYLON.Tmp.Matrix[1];
  33660. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33661. rotMatInv.multiplyToRef(rotMat, rotMat);
  33662. this._rotateWithMatrix(rotMat, space, mesh);
  33663. };
  33664. /**
  33665. * Set the euler rotation of the bone in local of world space.
  33666. * @param rotation The euler rotation that the bone should be set to.
  33667. * @param space The space that the rotation is in.
  33668. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33669. */
  33670. Bone.prototype.setRotation = function (rotation, space, mesh) {
  33671. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33672. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  33673. };
  33674. /**
  33675. * Set the quaternion rotation of the bone in local of world space.
  33676. * @param quat The quaternion rotation that the bone should be set to.
  33677. * @param space The space that the rotation is in.
  33678. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33679. */
  33680. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  33681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33682. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33683. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33684. var rotMat = BABYLON.Tmp.Matrix[1];
  33685. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  33686. rotMatInv.multiplyToRef(rotMat, rotMat);
  33687. this._rotateWithMatrix(rotMat, space, mesh);
  33688. };
  33689. /**
  33690. * Set the rotation matrix of the bone in local of world space.
  33691. * @param rotMat The rotation matrix that the bone should be set to.
  33692. * @param space The space that the rotation is in.
  33693. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33694. */
  33695. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  33696. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33697. var rotMatInv = BABYLON.Tmp.Matrix[0];
  33698. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  33699. var rotMat2 = BABYLON.Tmp.Matrix[1];
  33700. rotMat2.copyFrom(rotMat);
  33701. rotMatInv.multiplyToRef(rotMat, rotMat2);
  33702. this._rotateWithMatrix(rotMat2, space, mesh);
  33703. };
  33704. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  33705. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33706. var lmat = this.getLocalMatrix();
  33707. var lx = lmat.m[12];
  33708. var ly = lmat.m[13];
  33709. var lz = lmat.m[14];
  33710. var parent = this.getParent();
  33711. var parentScale = BABYLON.Tmp.Matrix[3];
  33712. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  33713. if (parent) {
  33714. if (space == BABYLON.Space.WORLD) {
  33715. if (mesh) {
  33716. parentScale.copyFrom(mesh.getWorldMatrix());
  33717. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  33718. }
  33719. else {
  33720. parentScale.copyFrom(parent.getAbsoluteTransform());
  33721. }
  33722. }
  33723. else {
  33724. parentScale = parent._scaleMatrix;
  33725. }
  33726. parentScaleInv.copyFrom(parentScale);
  33727. parentScaleInv.invert();
  33728. lmat.multiplyToRef(parentScale, lmat);
  33729. lmat.multiplyToRef(rmat, lmat);
  33730. lmat.multiplyToRef(parentScaleInv, lmat);
  33731. }
  33732. else {
  33733. if (space == BABYLON.Space.WORLD && mesh) {
  33734. parentScale.copyFrom(mesh.getWorldMatrix());
  33735. parentScaleInv.copyFrom(parentScale);
  33736. parentScaleInv.invert();
  33737. lmat.multiplyToRef(parentScale, lmat);
  33738. lmat.multiplyToRef(rmat, lmat);
  33739. lmat.multiplyToRef(parentScaleInv, lmat);
  33740. }
  33741. else {
  33742. lmat.multiplyToRef(rmat, lmat);
  33743. }
  33744. }
  33745. lmat.m[12] = lx;
  33746. lmat.m[13] = ly;
  33747. lmat.m[14] = lz;
  33748. this.computeAbsoluteTransforms();
  33749. this.markAsDirty();
  33750. };
  33751. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  33752. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33753. if (space == BABYLON.Space.WORLD) {
  33754. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33755. scaleMatrix.copyFrom(this._scaleMatrix);
  33756. rotMatInv.copyFrom(this.getAbsoluteTransform());
  33757. if (mesh) {
  33758. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  33759. var meshScale = BABYLON.Tmp.Matrix[3];
  33760. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  33761. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  33762. }
  33763. rotMatInv.invert();
  33764. scaleMatrix.m[0] *= this._scalingDeterminant;
  33765. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33766. }
  33767. else {
  33768. rotMatInv.copyFrom(this.getLocalMatrix());
  33769. rotMatInv.invert();
  33770. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  33771. scaleMatrix.copyFrom(this._scaleMatrix);
  33772. if (this._parent) {
  33773. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  33774. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  33775. pscaleMatrix.invert();
  33776. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  33777. }
  33778. else {
  33779. scaleMatrix.m[0] *= this._scalingDeterminant;
  33780. }
  33781. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  33782. }
  33783. };
  33784. /**
  33785. * Get the scale of the bone
  33786. * @returns the scale of the bone
  33787. */
  33788. Bone.prototype.getScale = function () {
  33789. return this._scaleVector.clone();
  33790. };
  33791. /**
  33792. * Copy the scale of the bone to a vector3.
  33793. * @param result The vector3 to copy the scale to
  33794. */
  33795. Bone.prototype.getScaleToRef = function (result) {
  33796. result.copyFrom(this._scaleVector);
  33797. };
  33798. /**
  33799. * Get the position of the bone in local or world space.
  33800. * @param space The space that the returned position is in.
  33801. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33802. * @returns The position of the bone
  33803. */
  33804. Bone.prototype.getPosition = function (space, mesh) {
  33805. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33806. var pos = BABYLON.Vector3.Zero();
  33807. this.getPositionToRef(space, mesh, pos);
  33808. return pos;
  33809. };
  33810. /**
  33811. * Copy the position of the bone to a vector3 in local or world space.
  33812. * @param space The space that the returned position is in.
  33813. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33814. * @param result The vector3 to copy the position to.
  33815. */
  33816. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  33817. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33818. if (space == BABYLON.Space.LOCAL) {
  33819. var lm = this.getLocalMatrix();
  33820. result.x = lm.m[12];
  33821. result.y = lm.m[13];
  33822. result.z = lm.m[14];
  33823. }
  33824. else {
  33825. var wm;
  33826. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33827. if (mesh) {
  33828. wm = mesh.getWorldMatrix();
  33829. }
  33830. this._skeleton.computeAbsoluteTransforms();
  33831. var tmat = BABYLON.Tmp.Matrix[0];
  33832. if (mesh) {
  33833. tmat.copyFrom(this.getAbsoluteTransform());
  33834. tmat.multiplyToRef(wm, tmat);
  33835. }
  33836. else {
  33837. tmat = this.getAbsoluteTransform();
  33838. }
  33839. result.x = tmat.m[12];
  33840. result.y = tmat.m[13];
  33841. result.z = tmat.m[14];
  33842. }
  33843. };
  33844. /**
  33845. * Get the absolute position of the bone (world space).
  33846. * @param mesh The mesh that this bone is attached to.
  33847. * @returns The absolute position of the bone
  33848. */
  33849. Bone.prototype.getAbsolutePosition = function (mesh) {
  33850. var pos = BABYLON.Vector3.Zero();
  33851. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  33852. return pos;
  33853. };
  33854. /**
  33855. * Copy the absolute position of the bone (world space) to the result param.
  33856. * @param mesh The mesh that this bone is attached to.
  33857. * @param result The vector3 to copy the absolute position to.
  33858. */
  33859. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  33860. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  33861. };
  33862. /**
  33863. * Compute the absolute transforms of this bone and its children.
  33864. */
  33865. Bone.prototype.computeAbsoluteTransforms = function () {
  33866. if (this._parent) {
  33867. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33868. }
  33869. else {
  33870. this._absoluteTransform.copyFrom(this._localMatrix);
  33871. var poseMatrix = this._skeleton.getPoseMatrix();
  33872. if (poseMatrix) {
  33873. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  33874. }
  33875. }
  33876. var children = this.children;
  33877. var len = children.length;
  33878. for (var i = 0; i < len; i++) {
  33879. children[i].computeAbsoluteTransforms();
  33880. }
  33881. };
  33882. Bone.prototype._syncScaleVector = function () {
  33883. var lm = this.getLocalMatrix();
  33884. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  33885. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  33886. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  33887. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  33888. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  33889. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  33890. this._scaleVector.x = xs * Math.sqrt(xsq);
  33891. this._scaleVector.y = ys * Math.sqrt(ysq);
  33892. this._scaleVector.z = zs * Math.sqrt(zsq);
  33893. if (this._parent) {
  33894. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  33895. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  33896. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  33897. }
  33898. 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);
  33899. };
  33900. /**
  33901. * Get the world direction from an axis that is in the local space of the bone.
  33902. * @param localAxis The local direction that is used to compute the world direction.
  33903. * @param mesh The mesh that this bone is attached to.
  33904. * @returns The world direction
  33905. */
  33906. Bone.prototype.getDirection = function (localAxis, mesh) {
  33907. var result = BABYLON.Vector3.Zero();
  33908. this.getDirectionToRef(localAxis, mesh, result);
  33909. return result;
  33910. };
  33911. /**
  33912. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  33913. * @param localAxis The local direction that is used to compute the world direction.
  33914. * @param mesh The mesh that this bone is attached to.
  33915. * @param result The vector3 that the world direction will be copied to.
  33916. */
  33917. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  33918. var wm;
  33919. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  33920. if (mesh) {
  33921. wm = mesh.getWorldMatrix();
  33922. }
  33923. this._skeleton.computeAbsoluteTransforms();
  33924. var mat = BABYLON.Tmp.Matrix[0];
  33925. mat.copyFrom(this.getAbsoluteTransform());
  33926. if (mesh) {
  33927. mat.multiplyToRef(wm, mat);
  33928. }
  33929. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  33930. result.normalize();
  33931. };
  33932. /**
  33933. * Get the euler rotation of the bone in local or world space.
  33934. * @param space The space that the rotation should be in.
  33935. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33936. * @returns The euler rotation
  33937. */
  33938. Bone.prototype.getRotation = function (space, mesh) {
  33939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33940. var result = BABYLON.Vector3.Zero();
  33941. this.getRotationToRef(space, mesh, result);
  33942. return result;
  33943. };
  33944. /**
  33945. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  33946. * @param space The space that the rotation should be in.
  33947. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33948. * @param result The vector3 that the rotation should be copied to.
  33949. */
  33950. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  33951. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33952. var quat = BABYLON.Tmp.Quaternion[0];
  33953. this.getRotationQuaternionToRef(space, mesh, quat);
  33954. quat.toEulerAnglesToRef(result);
  33955. };
  33956. /**
  33957. * Get the quaternion rotation of the bone in either local or world space.
  33958. * @param space The space that the rotation should be in.
  33959. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33960. * @returns The quaternion rotation
  33961. */
  33962. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  33963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33964. var result = BABYLON.Quaternion.Identity();
  33965. this.getRotationQuaternionToRef(space, mesh, result);
  33966. return result;
  33967. };
  33968. /**
  33969. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  33970. * @param space The space that the rotation should be in.
  33971. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33972. * @param result The quaternion that the rotation should be copied to.
  33973. */
  33974. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  33975. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  33976. if (space == BABYLON.Space.LOCAL) {
  33977. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33978. }
  33979. else {
  33980. var mat = BABYLON.Tmp.Matrix[0];
  33981. var amat = this.getAbsoluteTransform();
  33982. if (mesh) {
  33983. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  33984. }
  33985. else {
  33986. mat.copyFrom(amat);
  33987. }
  33988. mat.m[0] *= this._scalingDeterminant;
  33989. mat.m[1] *= this._scalingDeterminant;
  33990. mat.m[2] *= this._scalingDeterminant;
  33991. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  33992. }
  33993. };
  33994. /**
  33995. * Get the rotation matrix of the bone in local or world space.
  33996. * @param space The space that the rotation should be in.
  33997. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  33998. * @returns The rotation matrix
  33999. */
  34000. Bone.prototype.getRotationMatrix = function (space, mesh) {
  34001. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34002. var result = BABYLON.Matrix.Identity();
  34003. this.getRotationMatrixToRef(space, mesh, result);
  34004. return result;
  34005. };
  34006. /**
  34007. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  34008. * @param space The space that the rotation should be in.
  34009. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34010. * @param result The quaternion that the rotation should be copied to.
  34011. */
  34012. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  34013. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34014. if (space == BABYLON.Space.LOCAL) {
  34015. this.getLocalMatrix().getRotationMatrixToRef(result);
  34016. }
  34017. else {
  34018. var mat = BABYLON.Tmp.Matrix[0];
  34019. var amat = this.getAbsoluteTransform();
  34020. if (mesh) {
  34021. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34022. }
  34023. else {
  34024. mat.copyFrom(amat);
  34025. }
  34026. mat.m[0] *= this._scalingDeterminant;
  34027. mat.m[1] *= this._scalingDeterminant;
  34028. mat.m[2] *= this._scalingDeterminant;
  34029. mat.getRotationMatrixToRef(result);
  34030. }
  34031. };
  34032. /**
  34033. * Get the world position of a point that is in the local space of the bone.
  34034. * @param position The local position
  34035. * @param mesh The mesh that this bone is attached to.
  34036. * @returns The world position
  34037. */
  34038. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  34039. var result = BABYLON.Vector3.Zero();
  34040. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  34041. return result;
  34042. };
  34043. /**
  34044. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  34045. * @param position The local position
  34046. * @param mesh The mesh that this bone is attached to.
  34047. * @param result The vector3 that the world position should be copied to.
  34048. */
  34049. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  34050. var wm;
  34051. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34052. if (mesh) {
  34053. wm = mesh.getWorldMatrix();
  34054. }
  34055. this._skeleton.computeAbsoluteTransforms();
  34056. var tmat = BABYLON.Tmp.Matrix[0];
  34057. if (mesh) {
  34058. tmat.copyFrom(this.getAbsoluteTransform());
  34059. tmat.multiplyToRef(wm, tmat);
  34060. }
  34061. else {
  34062. tmat = this.getAbsoluteTransform();
  34063. }
  34064. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34065. };
  34066. /**
  34067. * Get the local position of a point that is in world space.
  34068. * @param position The world position
  34069. * @param mesh The mesh that this bone is attached to.
  34070. * @returns The local position
  34071. */
  34072. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  34073. var result = BABYLON.Vector3.Zero();
  34074. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  34075. return result;
  34076. };
  34077. /**
  34078. * Get the local position of a point that is in world space and copy it to the result param.
  34079. * @param position The world position
  34080. * @param mesh The mesh that this bone is attached to.
  34081. * @param result The vector3 that the local position should be copied to.
  34082. */
  34083. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  34084. var wm;
  34085. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34086. if (mesh) {
  34087. wm = mesh.getWorldMatrix();
  34088. }
  34089. this._skeleton.computeAbsoluteTransforms();
  34090. var tmat = BABYLON.Tmp.Matrix[0];
  34091. tmat.copyFrom(this.getAbsoluteTransform());
  34092. if (mesh) {
  34093. tmat.multiplyToRef(wm, tmat);
  34094. }
  34095. tmat.invert();
  34096. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34097. };
  34098. return Bone;
  34099. }(BABYLON.Node));
  34100. BABYLON.Bone = Bone;
  34101. })(BABYLON || (BABYLON = {}));
  34102. //# sourceMappingURL=babylon.bone.js.map
  34103. var BABYLON;
  34104. (function (BABYLON) {
  34105. var BoneIKController = (function () {
  34106. function BoneIKController(mesh, bone, options) {
  34107. this.targetPosition = BABYLON.Vector3.Zero();
  34108. this.poleTargetPosition = BABYLON.Vector3.Zero();
  34109. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  34110. this.poleAngle = 0;
  34111. this.slerpAmount = 1;
  34112. this._bone1Quat = BABYLON.Quaternion.Identity();
  34113. this._bone1Mat = BABYLON.Matrix.Identity();
  34114. this._bone2Ang = Math.PI;
  34115. this._maxAngle = Math.PI;
  34116. this._tmpVec1 = BABYLON.Vector3.Zero();
  34117. this._tmpVec2 = BABYLON.Vector3.Zero();
  34118. this._tmpVec3 = BABYLON.Vector3.Zero();
  34119. this._tmpVec4 = BABYLON.Vector3.Zero();
  34120. this._tmpVec5 = BABYLON.Vector3.Zero();
  34121. this._tmpMat1 = BABYLON.Matrix.Identity();
  34122. this._tmpMat2 = BABYLON.Matrix.Identity();
  34123. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  34124. this._rightHandedSystem = false;
  34125. this._bendAxis = BABYLON.Vector3.Right();
  34126. this._slerping = false;
  34127. this._adjustRoll = 0;
  34128. this._bone2 = bone;
  34129. this._bone1 = bone.getParent();
  34130. this.mesh = mesh;
  34131. var bonePos = bone.getPosition();
  34132. if (bone.getAbsoluteTransform().determinant() > 0) {
  34133. this._rightHandedSystem = true;
  34134. this._bendAxis.x = 0;
  34135. this._bendAxis.y = 0;
  34136. this._bendAxis.z = -1;
  34137. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  34138. this._adjustRoll = Math.PI * .5;
  34139. this._bendAxis.z = 1;
  34140. }
  34141. }
  34142. if (this._bone1.length) {
  34143. var boneScale1 = this._bone1.getScale();
  34144. var boneScale2 = this._bone2.getScale();
  34145. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  34146. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  34147. }
  34148. else if (this._bone1.children[0]) {
  34149. mesh.computeWorldMatrix(true);
  34150. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  34151. var pos2 = this._bone2.getAbsolutePosition(mesh);
  34152. var pos3 = this._bone1.getAbsolutePosition(mesh);
  34153. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  34154. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  34155. }
  34156. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  34157. this.maxAngle = Math.PI;
  34158. if (options) {
  34159. if (options.targetMesh) {
  34160. this.targetMesh = options.targetMesh;
  34161. this.targetMesh.computeWorldMatrix(true);
  34162. }
  34163. if (options.poleTargetMesh) {
  34164. this.poleTargetMesh = options.poleTargetMesh;
  34165. this.poleTargetMesh.computeWorldMatrix(true);
  34166. }
  34167. else if (options.poleTargetBone) {
  34168. this.poleTargetBone = options.poleTargetBone;
  34169. }
  34170. else if (this._bone1.getParent()) {
  34171. this.poleTargetBone = this._bone1.getParent();
  34172. }
  34173. if (options.poleTargetLocalOffset) {
  34174. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  34175. }
  34176. if (options.poleAngle) {
  34177. this.poleAngle = options.poleAngle;
  34178. }
  34179. if (options.bendAxis) {
  34180. this._bendAxis.copyFrom(options.bendAxis);
  34181. }
  34182. if (options.maxAngle) {
  34183. this.maxAngle = options.maxAngle;
  34184. }
  34185. if (options.slerpAmount) {
  34186. this.slerpAmount = options.slerpAmount;
  34187. }
  34188. }
  34189. }
  34190. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  34191. get: function () {
  34192. return this._maxAngle;
  34193. },
  34194. set: function (value) {
  34195. this._setMaxAngle(value);
  34196. },
  34197. enumerable: true,
  34198. configurable: true
  34199. });
  34200. BoneIKController.prototype._setMaxAngle = function (ang) {
  34201. if (ang < 0) {
  34202. ang = 0;
  34203. }
  34204. if (ang > Math.PI || ang == undefined) {
  34205. ang = Math.PI;
  34206. }
  34207. this._maxAngle = ang;
  34208. var a = this._bone1Length;
  34209. var b = this._bone2Length;
  34210. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  34211. };
  34212. BoneIKController.prototype.update = function () {
  34213. var bone1 = this._bone1;
  34214. var target = this.targetPosition;
  34215. var poleTarget = this.poleTargetPosition;
  34216. var mat1 = this._tmpMat1;
  34217. var mat2 = this._tmpMat2;
  34218. if (this.targetMesh) {
  34219. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34220. }
  34221. if (this.poleTargetBone) {
  34222. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34223. }
  34224. else if (this.poleTargetMesh) {
  34225. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34226. }
  34227. var bonePos = this._tmpVec1;
  34228. var zaxis = this._tmpVec2;
  34229. var xaxis = this._tmpVec3;
  34230. var yaxis = this._tmpVec4;
  34231. var upAxis = this._tmpVec5;
  34232. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34233. poleTarget.subtractToRef(bonePos, upAxis);
  34234. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34235. upAxis.y = 1;
  34236. }
  34237. else {
  34238. upAxis.normalize();
  34239. }
  34240. target.subtractToRef(bonePos, yaxis);
  34241. yaxis.normalize();
  34242. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34243. zaxis.normalize();
  34244. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34245. xaxis.normalize();
  34246. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34247. var a = this._bone1Length;
  34248. var b = this._bone2Length;
  34249. var c = BABYLON.Vector3.Distance(bonePos, target);
  34250. if (this._maxReach > 0) {
  34251. c = Math.min(this._maxReach, c);
  34252. }
  34253. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34254. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34255. if (acosa > 1) {
  34256. acosa = 1;
  34257. }
  34258. if (acosb > 1) {
  34259. acosb = 1;
  34260. }
  34261. if (acosa < -1) {
  34262. acosa = -1;
  34263. }
  34264. if (acosb < -1) {
  34265. acosb = -1;
  34266. }
  34267. var angA = Math.acos(acosa);
  34268. var angB = Math.acos(acosb);
  34269. var angC = -angA - angB;
  34270. if (this._rightHandedSystem) {
  34271. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34272. mat2.multiplyToRef(mat1, mat1);
  34273. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34274. mat2.multiplyToRef(mat1, mat1);
  34275. }
  34276. else {
  34277. this._tmpVec1.copyFrom(this._bendAxis);
  34278. this._tmpVec1.x *= -1;
  34279. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  34280. mat2.multiplyToRef(mat1, mat1);
  34281. }
  34282. if (this.poleAngle) {
  34283. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34284. mat1.multiplyToRef(mat2, mat1);
  34285. }
  34286. if (this.slerpAmount < 1) {
  34287. if (!this._slerping) {
  34288. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34289. }
  34290. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  34291. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  34292. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34293. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34294. this._slerping = true;
  34295. }
  34296. else {
  34297. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34298. this._bone1Mat.copyFrom(mat1);
  34299. this._slerping = false;
  34300. }
  34301. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34302. this._bone2Ang = angC;
  34303. };
  34304. return BoneIKController;
  34305. }());
  34306. BABYLON.BoneIKController = BoneIKController;
  34307. })(BABYLON || (BABYLON = {}));
  34308. //# sourceMappingURL=babylon.boneIKController.js.map
  34309. var BABYLON;
  34310. (function (BABYLON) {
  34311. var BoneLookController = (function () {
  34312. /**
  34313. * Create a BoneLookController
  34314. * @param mesh the mesh that the bone belongs to
  34315. * @param bone the bone that will be looking to the target
  34316. * @param target the target Vector3 to look at
  34317. * @param settings optional settings:
  34318. * - maxYaw: the maximum angle the bone will yaw to
  34319. * - minYaw: the minimum angle the bone will yaw to
  34320. * - maxPitch: the maximum angle the bone will pitch to
  34321. * - minPitch: the minimum angle the bone will yaw to
  34322. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  34323. * - upAxis: the up axis of the coordinate system
  34324. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34325. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  34326. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  34327. * - adjustYaw: used to make an adjustment to the yaw of the bone
  34328. * - adjustPitch: used to make an adjustment to the pitch of the bone
  34329. * - adjustRoll: used to make an adjustment to the roll of the bone
  34330. **/
  34331. function BoneLookController(mesh, bone, target, options) {
  34332. /**
  34333. * The up axis of the coordinate system that is used when the bone is rotated.
  34334. */
  34335. this.upAxis = BABYLON.Vector3.Up();
  34336. /**
  34337. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34338. */
  34339. this.upAxisSpace = BABYLON.Space.LOCAL;
  34340. /**
  34341. * Used to make an adjustment to the yaw of the bone.
  34342. */
  34343. this.adjustYaw = 0;
  34344. /**
  34345. * Used to make an adjustment to the pitch of the bone.
  34346. */
  34347. this.adjustPitch = 0;
  34348. /**
  34349. * Used to make an adjustment to the roll of the bone.
  34350. */
  34351. this.adjustRoll = 0;
  34352. /**
  34353. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  34354. */
  34355. this.slerpAmount = 1;
  34356. this._boneQuat = BABYLON.Quaternion.Identity();
  34357. this._slerping = false;
  34358. this._firstFrameSkipped = false;
  34359. this._fowardAxis = BABYLON.Vector3.Forward();
  34360. this.mesh = mesh;
  34361. this.bone = bone;
  34362. this.target = target;
  34363. if (options) {
  34364. if (options.adjustYaw) {
  34365. this.adjustYaw = options.adjustYaw;
  34366. }
  34367. if (options.adjustPitch) {
  34368. this.adjustPitch = options.adjustPitch;
  34369. }
  34370. if (options.adjustRoll) {
  34371. this.adjustRoll = options.adjustRoll;
  34372. }
  34373. if (options.maxYaw != null) {
  34374. this.maxYaw = options.maxYaw;
  34375. }
  34376. else {
  34377. this.maxYaw = Math.PI;
  34378. }
  34379. if (options.minYaw != null) {
  34380. this.minYaw = options.minYaw;
  34381. }
  34382. else {
  34383. this.minYaw = -Math.PI;
  34384. }
  34385. if (options.maxPitch != null) {
  34386. this.maxPitch = options.maxPitch;
  34387. }
  34388. else {
  34389. this.maxPitch = Math.PI;
  34390. }
  34391. if (options.minPitch != null) {
  34392. this.minPitch = options.minPitch;
  34393. }
  34394. else {
  34395. this.minPitch = -Math.PI;
  34396. }
  34397. if (options.slerpAmount != null) {
  34398. this.slerpAmount = options.slerpAmount;
  34399. }
  34400. if (options.upAxis != null) {
  34401. this.upAxis = options.upAxis;
  34402. }
  34403. if (options.upAxisSpace != null) {
  34404. this.upAxisSpace = options.upAxisSpace;
  34405. }
  34406. if (options.yawAxis != null || options.pitchAxis != null) {
  34407. var newYawAxis = BABYLON.Axis.Y;
  34408. var newPitchAxis = BABYLON.Axis.X;
  34409. if (options.yawAxis != null) {
  34410. newYawAxis = options.yawAxis.clone();
  34411. newYawAxis.normalize();
  34412. }
  34413. if (options.pitchAxis != null) {
  34414. newPitchAxis = options.pitchAxis.clone();
  34415. newPitchAxis.normalize();
  34416. }
  34417. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  34418. this._transformYawPitch = BABYLON.Matrix.Identity();
  34419. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  34420. this._transformYawPitchInv = this._transformYawPitch.clone();
  34421. this._transformYawPitch.invert();
  34422. }
  34423. }
  34424. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  34425. this.upAxisSpace = BABYLON.Space.LOCAL;
  34426. }
  34427. }
  34428. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  34429. /**
  34430. * Get/set the minimum yaw angle that the bone can look to.
  34431. */
  34432. get: function () {
  34433. return this._minYaw;
  34434. },
  34435. set: function (value) {
  34436. this._minYaw = value;
  34437. this._minYawSin = Math.sin(value);
  34438. this._minYawCos = Math.cos(value);
  34439. if (this._maxYaw != null) {
  34440. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34441. this._yawRange = this._maxYaw - this._minYaw;
  34442. }
  34443. },
  34444. enumerable: true,
  34445. configurable: true
  34446. });
  34447. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  34448. /**
  34449. * Get/set the maximum yaw angle that the bone can look to.
  34450. */
  34451. get: function () {
  34452. return this._maxYaw;
  34453. },
  34454. set: function (value) {
  34455. this._maxYaw = value;
  34456. this._maxYawSin = Math.sin(value);
  34457. this._maxYawCos = Math.cos(value);
  34458. if (this._minYaw != null) {
  34459. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  34460. this._yawRange = this._maxYaw - this._minYaw;
  34461. }
  34462. },
  34463. enumerable: true,
  34464. configurable: true
  34465. });
  34466. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  34467. /**
  34468. * Get/set the minimum pitch angle that the bone can look to.
  34469. */
  34470. get: function () {
  34471. return this._minPitch;
  34472. },
  34473. set: function (value) {
  34474. this._minPitch = value;
  34475. this._minPitchTan = Math.tan(value);
  34476. },
  34477. enumerable: true,
  34478. configurable: true
  34479. });
  34480. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  34481. /**
  34482. * Get/set the maximum pitch angle that the bone can look to.
  34483. */
  34484. get: function () {
  34485. return this._maxPitch;
  34486. },
  34487. set: function (value) {
  34488. this._maxPitch = value;
  34489. this._maxPitchTan = Math.tan(value);
  34490. },
  34491. enumerable: true,
  34492. configurable: true
  34493. });
  34494. /**
  34495. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  34496. */
  34497. BoneLookController.prototype.update = function () {
  34498. //skip the first frame when slerping so that the mesh rotation is correct
  34499. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  34500. this._firstFrameSkipped = true;
  34501. return;
  34502. }
  34503. var bone = this.bone;
  34504. var bonePos = BoneLookController._tmpVecs[0];
  34505. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  34506. var target = this.target;
  34507. var _tmpMat1 = BoneLookController._tmpMats[0];
  34508. var _tmpMat2 = BoneLookController._tmpMats[1];
  34509. var mesh = this.mesh;
  34510. var parentBone = bone.getParent();
  34511. var upAxis = BoneLookController._tmpVecs[1];
  34512. upAxis.copyFrom(this.upAxis);
  34513. if (this.upAxisSpace == BABYLON.Space.BONE) {
  34514. if (this._transformYawPitch) {
  34515. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  34516. }
  34517. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  34518. }
  34519. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  34520. mesh.getDirectionToRef(upAxis, upAxis);
  34521. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  34522. upAxis.normalize();
  34523. }
  34524. }
  34525. var checkYaw = false;
  34526. var checkPitch = false;
  34527. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  34528. checkYaw = true;
  34529. }
  34530. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  34531. checkPitch = true;
  34532. }
  34533. if (checkYaw || checkPitch) {
  34534. var _tmpMat3 = BoneLookController._tmpMats[2];
  34535. var _tmpMat3Inv = BoneLookController._tmpMats[3];
  34536. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  34537. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, _tmpMat3);
  34538. }
  34539. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  34540. _tmpMat3.copyFrom(mesh.getWorldMatrix());
  34541. }
  34542. else {
  34543. var forwardAxis = BoneLookController._tmpVecs[2];
  34544. forwardAxis.copyFrom(this._fowardAxis);
  34545. if (this._transformYawPitch) {
  34546. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  34547. }
  34548. if (parentBone) {
  34549. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  34550. }
  34551. else {
  34552. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  34553. }
  34554. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  34555. rightAxis.normalize();
  34556. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  34557. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, _tmpMat3);
  34558. }
  34559. _tmpMat3.invertToRef(_tmpMat3Inv);
  34560. var xzlen;
  34561. if (checkPitch) {
  34562. var localTarget = BoneLookController._tmpVecs[3];
  34563. BABYLON.Vector3.TransformCoordinatesToRef(target.subtract(bonePos), _tmpMat3Inv, localTarget);
  34564. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  34565. var pitch = Math.atan2(localTarget.y, xzlen);
  34566. var newPitch = pitch;
  34567. if (pitch > this._maxPitch) {
  34568. localTarget.y = this._maxPitchTan * xzlen;
  34569. newPitch = this._maxPitch;
  34570. }
  34571. else if (pitch < this._minPitch) {
  34572. localTarget.y = this._minPitchTan * xzlen;
  34573. newPitch = this._minPitch;
  34574. }
  34575. if (pitch != newPitch) {
  34576. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, _tmpMat3, localTarget);
  34577. localTarget.addInPlace(bonePos);
  34578. target = localTarget;
  34579. }
  34580. }
  34581. if (checkYaw) {
  34582. var localTarget = BoneLookController._tmpVecs[4];
  34583. BABYLON.Vector3.TransformCoordinatesToRef(target.subtract(bonePos), _tmpMat3Inv, localTarget);
  34584. var yaw = Math.atan2(localTarget.x, localTarget.z);
  34585. var newYaw = yaw;
  34586. if (yaw > this._maxYaw || yaw < this._minYaw) {
  34587. if (xzlen == null) {
  34588. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  34589. }
  34590. if (this._yawRange > Math.PI) {
  34591. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  34592. localTarget.z = this._maxYawCos * xzlen;
  34593. localTarget.x = this._maxYawSin * xzlen;
  34594. newYaw = this._maxYaw;
  34595. }
  34596. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  34597. localTarget.z = this._minYawCos * xzlen;
  34598. localTarget.x = this._minYawSin * xzlen;
  34599. newYaw = this._minYaw;
  34600. }
  34601. }
  34602. else {
  34603. if (yaw > this._maxYaw) {
  34604. localTarget.z = this._maxYawCos * xzlen;
  34605. localTarget.x = this._maxYawSin * xzlen;
  34606. newYaw = this._maxYaw;
  34607. }
  34608. else if (yaw < this._minYaw) {
  34609. localTarget.z = this._minYawCos * xzlen;
  34610. localTarget.x = this._minYawSin * xzlen;
  34611. newYaw = this._minYaw;
  34612. }
  34613. }
  34614. }
  34615. if (this._slerping && this._yawRange > Math.PI) {
  34616. //are we going to be crossing into the min/max region
  34617. var _tmpVec8 = BoneLookController._tmpVecs[8];
  34618. _tmpVec8.copyFrom(BABYLON.Axis.Z);
  34619. if (this._transformYawPitch) {
  34620. BABYLON.Vector3.TransformCoordinatesToRef(_tmpVec8, this._transformYawPitchInv, _tmpVec8);
  34621. }
  34622. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  34623. this._boneQuat.toRotationMatrix(boneRotMat);
  34624. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  34625. BABYLON.Vector3.TransformCoordinatesToRef(_tmpVec8, boneRotMat, _tmpVec8);
  34626. BABYLON.Vector3.TransformCoordinatesToRef(_tmpVec8, _tmpMat3Inv, _tmpVec8);
  34627. var boneYaw = Math.atan2(_tmpVec8.x, _tmpVec8.z);
  34628. var ang1 = this._getAngleBetween(boneYaw, yaw);
  34629. var ang2 = this._getAngleBetween(boneYaw, this._midYawConstraint);
  34630. if (ang1 > ang2) {
  34631. if (xzlen == null) {
  34632. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  34633. }
  34634. var ang3 = this._getAngleBetween(boneYaw, this._maxYaw);
  34635. var ang4 = this._getAngleBetween(boneYaw, this._minYaw);
  34636. if (ang4 < ang3) {
  34637. newYaw = boneYaw + Math.PI * .75;
  34638. localTarget.z = Math.cos(newYaw) * xzlen;
  34639. localTarget.x = Math.sin(newYaw) * xzlen;
  34640. }
  34641. else {
  34642. newYaw = boneYaw - Math.PI * .75;
  34643. localTarget.z = Math.cos(newYaw) * xzlen;
  34644. localTarget.x = Math.sin(newYaw) * xzlen;
  34645. }
  34646. }
  34647. }
  34648. if (yaw != newYaw) {
  34649. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, _tmpMat3, localTarget);
  34650. localTarget.addInPlace(bonePos);
  34651. target = localTarget;
  34652. }
  34653. }
  34654. }
  34655. var zaxis = BoneLookController._tmpVecs[5];
  34656. var xaxis = BoneLookController._tmpVecs[6];
  34657. var yaxis = BoneLookController._tmpVecs[7];
  34658. var _tmpQuat = BoneLookController._tmpQuat;
  34659. target.subtractToRef(bonePos, zaxis);
  34660. zaxis.normalize();
  34661. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  34662. xaxis.normalize();
  34663. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  34664. yaxis.normalize();
  34665. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  34666. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  34667. return;
  34668. }
  34669. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  34670. return;
  34671. }
  34672. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  34673. return;
  34674. }
  34675. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  34676. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  34677. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  34678. }
  34679. if (this.slerpAmount < 1) {
  34680. if (!this._slerping) {
  34681. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  34682. }
  34683. if (this._transformYawPitch) {
  34684. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  34685. }
  34686. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  34687. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  34688. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  34689. this._slerping = true;
  34690. }
  34691. else {
  34692. if (this._transformYawPitch) {
  34693. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  34694. }
  34695. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  34696. this._slerping = false;
  34697. }
  34698. };
  34699. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  34700. var angDiff = ang2 - ang1;
  34701. angDiff %= Math.PI * 2;
  34702. if (angDiff > Math.PI) {
  34703. angDiff -= Math.PI * 2;
  34704. }
  34705. else if (angDiff < -Math.PI) {
  34706. angDiff += Math.PI * 2;
  34707. }
  34708. return angDiff;
  34709. };
  34710. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  34711. ang1 %= (2 * Math.PI);
  34712. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  34713. ang2 %= (2 * Math.PI);
  34714. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  34715. var ab = 0;
  34716. if (ang1 < ang2) {
  34717. ab = ang2 - ang1;
  34718. }
  34719. else {
  34720. ab = ang1 - ang2;
  34721. }
  34722. if (ab > Math.PI) {
  34723. ab = Math.PI * 2 - ab;
  34724. }
  34725. return ab;
  34726. };
  34727. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  34728. ang %= (2 * Math.PI);
  34729. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  34730. ang1 %= (2 * Math.PI);
  34731. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  34732. ang2 %= (2 * Math.PI);
  34733. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  34734. if (ang1 < ang2) {
  34735. if (ang > ang1 && ang < ang2) {
  34736. return true;
  34737. }
  34738. }
  34739. else {
  34740. if (ang > ang2 && ang < ang1) {
  34741. return true;
  34742. }
  34743. }
  34744. return false;
  34745. };
  34746. return BoneLookController;
  34747. }());
  34748. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  34749. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  34750. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  34751. BABYLON.BoneLookController = BoneLookController;
  34752. })(BABYLON || (BABYLON = {}));
  34753. //# sourceMappingURL=babylon.boneLookController.js.map
  34754. var BABYLON;
  34755. (function (BABYLON) {
  34756. var Skeleton = (function () {
  34757. function Skeleton(name, id, scene) {
  34758. this.name = name;
  34759. this.id = id;
  34760. this.bones = new Array();
  34761. this.needInitialSkinMatrix = false;
  34762. this._isDirty = true;
  34763. this._meshesWithPoseMatrix = new Array();
  34764. this._identity = BABYLON.Matrix.Identity();
  34765. this._ranges = {};
  34766. this._lastAbsoluteTransformsUpdateId = -1;
  34767. // Events
  34768. /**
  34769. * An event triggered before computing the skeleton's matrices
  34770. * @type {BABYLON.Observable}
  34771. */
  34772. this.onBeforeComputeObservable = new BABYLON.Observable();
  34773. this.bones = [];
  34774. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34775. scene.skeletons.push(this);
  34776. //make sure it will recalculate the matrix next time prepare is called.
  34777. this._isDirty = true;
  34778. }
  34779. // Members
  34780. Skeleton.prototype.getTransformMatrices = function (mesh) {
  34781. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  34782. return mesh._bonesTransformMatrices;
  34783. }
  34784. if (!this._transformMatrices) {
  34785. this.prepare();
  34786. }
  34787. return this._transformMatrices;
  34788. };
  34789. Skeleton.prototype.getScene = function () {
  34790. return this._scene;
  34791. };
  34792. // Methods
  34793. /**
  34794. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  34795. */
  34796. Skeleton.prototype.toString = function (fullDetails) {
  34797. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  34798. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  34799. if (fullDetails) {
  34800. ret += ", Ranges: {";
  34801. var first = true;
  34802. for (var name_1 in this._ranges) {
  34803. if (first) {
  34804. ret += ", ";
  34805. first = false;
  34806. }
  34807. ret += name_1;
  34808. }
  34809. ret += "}";
  34810. }
  34811. return ret;
  34812. };
  34813. /**
  34814. * Get bone's index searching by name
  34815. * @param {string} name is bone's name to search for
  34816. * @return {number} Indice of the bone. Returns -1 if not found
  34817. */
  34818. Skeleton.prototype.getBoneIndexByName = function (name) {
  34819. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  34820. if (this.bones[boneIndex].name === name) {
  34821. return boneIndex;
  34822. }
  34823. }
  34824. return -1;
  34825. };
  34826. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  34827. // check name not already in use
  34828. if (!this._ranges[name]) {
  34829. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  34830. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34831. if (this.bones[i].animations[0]) {
  34832. this.bones[i].animations[0].createRange(name, from, to);
  34833. }
  34834. }
  34835. }
  34836. };
  34837. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  34838. if (deleteFrames === void 0) { deleteFrames = true; }
  34839. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34840. if (this.bones[i].animations[0]) {
  34841. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  34842. }
  34843. }
  34844. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  34845. };
  34846. Skeleton.prototype.getAnimationRange = function (name) {
  34847. return this._ranges[name];
  34848. };
  34849. /**
  34850. * Returns as an Array, all AnimationRanges defined on this skeleton
  34851. */
  34852. Skeleton.prototype.getAnimationRanges = function () {
  34853. var animationRanges = [];
  34854. var name;
  34855. var i = 0;
  34856. for (name in this._ranges) {
  34857. animationRanges[i] = this._ranges[name];
  34858. i++;
  34859. }
  34860. return animationRanges;
  34861. };
  34862. /**
  34863. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  34864. */
  34865. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  34866. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  34867. if (this._ranges[name] || !source.getAnimationRange(name)) {
  34868. return false;
  34869. }
  34870. var ret = true;
  34871. var frameOffset = this._getHighestAnimationFrame() + 1;
  34872. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  34873. var boneDict = {};
  34874. var sourceBones = source.bones;
  34875. var nBones;
  34876. var i;
  34877. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  34878. boneDict[sourceBones[i].name] = sourceBones[i];
  34879. }
  34880. if (this.bones.length !== sourceBones.length) {
  34881. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  34882. ret = false;
  34883. }
  34884. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  34885. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  34886. var boneName = this.bones[i].name;
  34887. var sourceBone = boneDict[boneName];
  34888. if (sourceBone) {
  34889. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  34890. }
  34891. else {
  34892. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  34893. ret = false;
  34894. }
  34895. }
  34896. // do not call createAnimationRange(), since it also is done to bones, which was already done
  34897. var range = source.getAnimationRange(name);
  34898. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  34899. return ret;
  34900. };
  34901. Skeleton.prototype.returnToRest = function () {
  34902. for (var index = 0; index < this.bones.length; index++) {
  34903. this.bones[index].returnToRest();
  34904. }
  34905. };
  34906. Skeleton.prototype._getHighestAnimationFrame = function () {
  34907. var ret = 0;
  34908. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  34909. if (this.bones[i].animations[0]) {
  34910. var highest = this.bones[i].animations[0].getHighestFrame();
  34911. if (ret < highest) {
  34912. ret = highest;
  34913. }
  34914. }
  34915. }
  34916. return ret;
  34917. };
  34918. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  34919. var range = this.getAnimationRange(name);
  34920. if (!range) {
  34921. return null;
  34922. }
  34923. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  34924. };
  34925. Skeleton.prototype._markAsDirty = function () {
  34926. this._isDirty = true;
  34927. };
  34928. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  34929. this._meshesWithPoseMatrix.push(mesh);
  34930. };
  34931. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  34932. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  34933. if (index > -1) {
  34934. this._meshesWithPoseMatrix.splice(index, 1);
  34935. }
  34936. };
  34937. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  34938. this.onBeforeComputeObservable.notifyObservers(this);
  34939. for (var index = 0; index < this.bones.length; index++) {
  34940. var bone = this.bones[index];
  34941. var parentBone = bone.getParent();
  34942. if (parentBone) {
  34943. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  34944. }
  34945. else {
  34946. if (initialSkinMatrix) {
  34947. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  34948. }
  34949. else {
  34950. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  34951. }
  34952. }
  34953. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  34954. }
  34955. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  34956. };
  34957. Skeleton.prototype.prepare = function () {
  34958. if (!this._isDirty) {
  34959. return;
  34960. }
  34961. if (this.needInitialSkinMatrix) {
  34962. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  34963. var mesh = this._meshesWithPoseMatrix[index];
  34964. var poseMatrix = mesh.getPoseMatrix();
  34965. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  34966. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34967. }
  34968. if (this._synchronizedWithMesh !== mesh) {
  34969. this._synchronizedWithMesh = mesh;
  34970. // Prepare bones
  34971. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  34972. var bone = this.bones[boneIndex];
  34973. if (!bone.getParent()) {
  34974. var matrix = bone.getBaseMatrix();
  34975. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  34976. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  34977. }
  34978. }
  34979. }
  34980. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  34981. }
  34982. }
  34983. else {
  34984. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  34985. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  34986. }
  34987. this._computeTransformMatrices(this._transformMatrices, null);
  34988. }
  34989. this._isDirty = false;
  34990. this._scene._activeBones.addCount(this.bones.length, false);
  34991. };
  34992. Skeleton.prototype.getAnimatables = function () {
  34993. if (!this._animatables || this._animatables.length !== this.bones.length) {
  34994. this._animatables = [];
  34995. for (var index = 0; index < this.bones.length; index++) {
  34996. this._animatables.push(this.bones[index]);
  34997. }
  34998. }
  34999. return this._animatables;
  35000. };
  35001. Skeleton.prototype.clone = function (name, id) {
  35002. var result = new Skeleton(name, id || name, this._scene);
  35003. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35004. for (var index = 0; index < this.bones.length; index++) {
  35005. var source = this.bones[index];
  35006. var parentBone = null;
  35007. if (source.getParent()) {
  35008. var parentIndex = this.bones.indexOf(source.getParent());
  35009. parentBone = result.bones[parentIndex];
  35010. }
  35011. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  35012. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  35013. }
  35014. if (this._ranges) {
  35015. result._ranges = {};
  35016. for (var rangeName in this._ranges) {
  35017. result._ranges[rangeName] = this._ranges[rangeName].clone();
  35018. }
  35019. }
  35020. this._isDirty = true;
  35021. return result;
  35022. };
  35023. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  35024. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  35025. this.bones.forEach(function (bone) {
  35026. bone.animations.forEach(function (animation) {
  35027. animation.enableBlending = true;
  35028. animation.blendingSpeed = blendingSpeed;
  35029. });
  35030. });
  35031. };
  35032. Skeleton.prototype.dispose = function () {
  35033. this._meshesWithPoseMatrix = [];
  35034. // Animations
  35035. this.getScene().stopAnimation(this);
  35036. // Remove from scene
  35037. this.getScene().removeSkeleton(this);
  35038. };
  35039. Skeleton.prototype.serialize = function () {
  35040. var serializationObject = {};
  35041. serializationObject.name = this.name;
  35042. serializationObject.id = this.id;
  35043. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  35044. serializationObject.bones = [];
  35045. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35046. for (var index = 0; index < this.bones.length; index++) {
  35047. var bone = this.bones[index];
  35048. var serializedBone = {
  35049. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  35050. name: bone.name,
  35051. matrix: bone.getBaseMatrix().toArray(),
  35052. rest: bone.getRestPose().toArray()
  35053. };
  35054. serializationObject.bones.push(serializedBone);
  35055. if (bone.length) {
  35056. serializedBone.length = bone.length;
  35057. }
  35058. if (bone.animations && bone.animations.length > 0) {
  35059. serializedBone.animation = bone.animations[0].serialize();
  35060. }
  35061. serializationObject.ranges = [];
  35062. for (var name in this._ranges) {
  35063. var range = {};
  35064. range.name = name;
  35065. range.from = this._ranges[name].from;
  35066. range.to = this._ranges[name].to;
  35067. serializationObject.ranges.push(range);
  35068. }
  35069. }
  35070. return serializationObject;
  35071. };
  35072. Skeleton.Parse = function (parsedSkeleton, scene) {
  35073. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  35074. if (parsedSkeleton.dimensionsAtRest) {
  35075. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  35076. }
  35077. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  35078. var index;
  35079. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  35080. var parsedBone = parsedSkeleton.bones[index];
  35081. var parentBone = null;
  35082. if (parsedBone.parentBoneIndex > -1) {
  35083. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  35084. }
  35085. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  35086. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  35087. if (parsedBone.length) {
  35088. bone.length = parsedBone.length;
  35089. }
  35090. if (parsedBone.animation) {
  35091. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  35092. }
  35093. }
  35094. // placed after bones, so createAnimationRange can cascade down
  35095. if (parsedSkeleton.ranges) {
  35096. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  35097. var data = parsedSkeleton.ranges[index];
  35098. skeleton.createAnimationRange(data.name, data.from, data.to);
  35099. }
  35100. }
  35101. return skeleton;
  35102. };
  35103. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  35104. if (forceUpdate === void 0) { forceUpdate = false; }
  35105. var renderId = this._scene.getRenderId();
  35106. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  35107. this.bones[0].computeAbsoluteTransforms();
  35108. this._lastAbsoluteTransformsUpdateId = renderId;
  35109. }
  35110. };
  35111. Skeleton.prototype.getPoseMatrix = function () {
  35112. var poseMatrix;
  35113. if (this._meshesWithPoseMatrix.length > 0) {
  35114. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  35115. }
  35116. return poseMatrix;
  35117. };
  35118. return Skeleton;
  35119. }());
  35120. BABYLON.Skeleton = Skeleton;
  35121. })(BABYLON || (BABYLON = {}));
  35122. //# sourceMappingURL=babylon.skeleton.js.map
  35123. var BABYLON;
  35124. (function (BABYLON) {
  35125. var PostProcess = (function () {
  35126. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  35127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35128. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35129. this.name = name;
  35130. this.width = -1;
  35131. this.height = -1;
  35132. /*
  35133. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35134. Can only be used on a single postprocess or on the last one of a chain.
  35135. */
  35136. this.enablePixelPerfectMode = false;
  35137. this.samples = 1;
  35138. this._reusable = false;
  35139. this._textures = new BABYLON.SmartArray(2);
  35140. this._currentRenderTextureInd = 0;
  35141. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35142. // Events
  35143. /**
  35144. * An event triggered when the postprocess is activated.
  35145. * @type {BABYLON.Observable}
  35146. */
  35147. this.onActivateObservable = new BABYLON.Observable();
  35148. /**
  35149. * An event triggered when the postprocess changes its size.
  35150. * @type {BABYLON.Observable}
  35151. */
  35152. this.onSizeChangedObservable = new BABYLON.Observable();
  35153. /**
  35154. * An event triggered when the postprocess applies its effect.
  35155. * @type {BABYLON.Observable}
  35156. */
  35157. this.onApplyObservable = new BABYLON.Observable();
  35158. /**
  35159. * An event triggered before rendering the postprocess
  35160. * @type {BABYLON.Observable}
  35161. */
  35162. this.onBeforeRenderObservable = new BABYLON.Observable();
  35163. /**
  35164. * An event triggered after rendering the postprocess
  35165. * @type {BABYLON.Observable}
  35166. */
  35167. this.onAfterRenderObservable = new BABYLON.Observable();
  35168. if (camera != null) {
  35169. this._camera = camera;
  35170. this._scene = camera.getScene();
  35171. camera.attachPostProcess(this);
  35172. this._engine = this._scene.getEngine();
  35173. }
  35174. else {
  35175. this._engine = engine;
  35176. }
  35177. this._options = options;
  35178. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35179. this._reusable = reusable || false;
  35180. this._textureType = textureType;
  35181. this._samplers = samplers || [];
  35182. this._samplers.push("textureSampler");
  35183. this._fragmentUrl = fragmentUrl;
  35184. this._parameters = parameters || [];
  35185. this._parameters.push("scale");
  35186. this.updateEffect(defines);
  35187. }
  35188. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35189. set: function (callback) {
  35190. if (this._onActivateObserver) {
  35191. this.onActivateObservable.remove(this._onActivateObserver);
  35192. }
  35193. this._onActivateObserver = this.onActivateObservable.add(callback);
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35199. set: function (callback) {
  35200. if (this._onSizeChangedObserver) {
  35201. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35202. }
  35203. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. Object.defineProperty(PostProcess.prototype, "onApply", {
  35209. set: function (callback) {
  35210. if (this._onApplyObserver) {
  35211. this.onApplyObservable.remove(this._onApplyObserver);
  35212. }
  35213. this._onApplyObserver = this.onApplyObservable.add(callback);
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35219. set: function (callback) {
  35220. if (this._onBeforeRenderObserver) {
  35221. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35222. }
  35223. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35229. set: function (callback) {
  35230. if (this._onAfterRenderObserver) {
  35231. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35232. }
  35233. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. PostProcess.prototype.updateEffect = function (defines) {
  35239. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  35240. };
  35241. PostProcess.prototype.isReusable = function () {
  35242. return this._reusable;
  35243. };
  35244. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35245. PostProcess.prototype.markTextureDirty = function () {
  35246. this.width = -1;
  35247. };
  35248. PostProcess.prototype.activate = function (camera, sourceTexture) {
  35249. var _this = this;
  35250. camera = camera || this._camera;
  35251. var scene = camera.getScene();
  35252. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  35253. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35254. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35255. var desiredWidth = this._options.width || requiredWidth;
  35256. var desiredHeight = this._options.height || requiredHeight;
  35257. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  35258. if (!this._options.width) {
  35259. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  35260. }
  35261. if (!this._options.height) {
  35262. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  35263. }
  35264. }
  35265. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35266. if (this._textures.length > 0) {
  35267. for (var i = 0; i < this._textures.length; i++) {
  35268. this._engine._releaseTexture(this._textures.data[i]);
  35269. }
  35270. this._textures.reset();
  35271. }
  35272. this.width = desiredWidth;
  35273. this.height = desiredHeight;
  35274. var textureSize = { width: this.width, height: this.height };
  35275. var textureOptions = {
  35276. generateMipMaps: false,
  35277. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  35278. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  35279. samplingMode: this.renderTargetSamplingMode,
  35280. type: this._textureType
  35281. };
  35282. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35283. if (this._reusable) {
  35284. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35285. }
  35286. this.onSizeChangedObservable.notifyObservers(this);
  35287. }
  35288. this._textures.forEach(function (texture) {
  35289. if (texture.samples !== _this.samples) {
  35290. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35291. }
  35292. });
  35293. if (this.enablePixelPerfectMode) {
  35294. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35295. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  35296. }
  35297. else {
  35298. this._scaleRatio.copyFromFloats(1, 1);
  35299. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  35300. }
  35301. this.onActivateObservable.notifyObservers(camera);
  35302. // Clear
  35303. if (this.clearColor) {
  35304. this._engine.clear(this.clearColor, true, true, true);
  35305. }
  35306. else {
  35307. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  35308. }
  35309. if (this._reusable) {
  35310. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35311. }
  35312. };
  35313. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35314. get: function () {
  35315. return this._effect.isSupported;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. PostProcess.prototype.apply = function () {
  35321. // Check
  35322. if (!this._effect.isReady())
  35323. return null;
  35324. // States
  35325. this._engine.enableEffect(this._effect);
  35326. this._engine.setState(false);
  35327. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35328. this._engine.setDepthBuffer(false);
  35329. this._engine.setDepthWrite(false);
  35330. // Texture
  35331. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  35332. // Parameters
  35333. this._effect.setVector2("scale", this._scaleRatio);
  35334. this.onApplyObservable.notifyObservers(this._effect);
  35335. return this._effect;
  35336. };
  35337. PostProcess.prototype.dispose = function (camera) {
  35338. camera = camera || this._camera;
  35339. if (this._textures.length > 0) {
  35340. for (var i = 0; i < this._textures.length; i++) {
  35341. this._engine._releaseTexture(this._textures.data[i]);
  35342. }
  35343. this._textures.reset();
  35344. }
  35345. if (!camera) {
  35346. return;
  35347. }
  35348. camera.detachPostProcess(this);
  35349. var index = camera._postProcesses.indexOf(this);
  35350. if (index === 0 && camera._postProcesses.length > 0) {
  35351. this._camera._postProcesses[0].markTextureDirty();
  35352. }
  35353. this.onActivateObservable.clear();
  35354. this.onAfterRenderObservable.clear();
  35355. this.onApplyObservable.clear();
  35356. this.onBeforeRenderObservable.clear();
  35357. this.onSizeChangedObservable.clear();
  35358. };
  35359. return PostProcess;
  35360. }());
  35361. BABYLON.PostProcess = PostProcess;
  35362. })(BABYLON || (BABYLON = {}));
  35363. //# sourceMappingURL=babylon.postProcess.js.map
  35364. var BABYLON;
  35365. (function (BABYLON) {
  35366. var PostProcessManager = (function () {
  35367. function PostProcessManager(scene) {
  35368. this._vertexBuffers = {};
  35369. this._scene = scene;
  35370. }
  35371. PostProcessManager.prototype._prepareBuffers = function () {
  35372. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35373. return;
  35374. }
  35375. // VBO
  35376. var vertices = [];
  35377. vertices.push(1, 1);
  35378. vertices.push(-1, 1);
  35379. vertices.push(-1, -1);
  35380. vertices.push(1, -1);
  35381. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35382. // Indices
  35383. var indices = [];
  35384. indices.push(0);
  35385. indices.push(1);
  35386. indices.push(2);
  35387. indices.push(0);
  35388. indices.push(2);
  35389. indices.push(3);
  35390. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35391. };
  35392. // Methods
  35393. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  35394. var postProcesses = this._scene.activeCamera._postProcesses;
  35395. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35396. return false;
  35397. }
  35398. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  35399. return true;
  35400. };
  35401. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  35402. var engine = this._scene.getEngine();
  35403. for (var index = 0; index < postProcesses.length; index++) {
  35404. if (index < postProcesses.length - 1) {
  35405. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35406. }
  35407. else {
  35408. if (targetTexture) {
  35409. engine.bindFramebuffer(targetTexture);
  35410. }
  35411. else {
  35412. engine.restoreDefaultFramebuffer();
  35413. }
  35414. }
  35415. var pp = postProcesses[index];
  35416. var effect = pp.apply();
  35417. if (effect) {
  35418. pp.onBeforeRenderObservable.notifyObservers(effect);
  35419. // VBOs
  35420. this._prepareBuffers();
  35421. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35422. // Draw order
  35423. engine.draw(true, 0, 6);
  35424. pp.onAfterRenderObservable.notifyObservers(effect);
  35425. }
  35426. }
  35427. // Restore depth buffer
  35428. engine.setDepthBuffer(true);
  35429. engine.setDepthWrite(true);
  35430. };
  35431. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  35432. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  35433. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35434. return;
  35435. }
  35436. var engine = this._scene.getEngine();
  35437. for (var index = 0, len = postProcesses.length; index < len; index++) {
  35438. if (index < len - 1) {
  35439. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35440. }
  35441. else {
  35442. if (targetTexture) {
  35443. engine.bindFramebuffer(targetTexture, faceIndex);
  35444. }
  35445. else {
  35446. engine.restoreDefaultFramebuffer();
  35447. }
  35448. }
  35449. if (doNotPresent) {
  35450. break;
  35451. }
  35452. var pp = postProcesses[index];
  35453. var effect = pp.apply();
  35454. if (effect) {
  35455. pp.onBeforeRenderObservable.notifyObservers(effect);
  35456. // VBOs
  35457. this._prepareBuffers();
  35458. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  35459. // Draw order
  35460. engine.draw(true, 0, 6);
  35461. pp.onAfterRenderObservable.notifyObservers(effect);
  35462. }
  35463. }
  35464. // Restore depth buffer
  35465. engine.setDepthBuffer(true);
  35466. engine.setDepthWrite(true);
  35467. };
  35468. PostProcessManager.prototype.dispose = function () {
  35469. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  35470. if (buffer) {
  35471. buffer.dispose();
  35472. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  35473. }
  35474. if (this._indexBuffer) {
  35475. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35476. this._indexBuffer = null;
  35477. }
  35478. };
  35479. return PostProcessManager;
  35480. }());
  35481. BABYLON.PostProcessManager = PostProcessManager;
  35482. })(BABYLON || (BABYLON = {}));
  35483. //# sourceMappingURL=babylon.postProcessManager.js.map
  35484. var BABYLON;
  35485. (function (BABYLON) {
  35486. var PassPostProcess = (function (_super) {
  35487. __extends(PassPostProcess, _super);
  35488. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  35489. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  35490. }
  35491. return PassPostProcess;
  35492. }(BABYLON.PostProcess));
  35493. BABYLON.PassPostProcess = PassPostProcess;
  35494. })(BABYLON || (BABYLON = {}));
  35495. //# sourceMappingURL=babylon.passPostProcess.js.map
  35496. var BABYLON;
  35497. (function (BABYLON) {
  35498. /**
  35499. * This is a holder class for the physics joint created by the physics plugin.
  35500. * It holds a set of functions to control the underlying joint.
  35501. */
  35502. var PhysicsJoint = (function () {
  35503. function PhysicsJoint(type, jointData) {
  35504. this.type = type;
  35505. this.jointData = jointData;
  35506. jointData.nativeParams = jointData.nativeParams || {};
  35507. }
  35508. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  35509. get: function () {
  35510. return this._physicsJoint;
  35511. },
  35512. set: function (newJoint) {
  35513. if (this._physicsJoint) {
  35514. }
  35515. this._physicsJoint = newJoint;
  35516. },
  35517. enumerable: true,
  35518. configurable: true
  35519. });
  35520. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  35521. set: function (physicsPlugin) {
  35522. this._physicsPlugin = physicsPlugin;
  35523. },
  35524. enumerable: true,
  35525. configurable: true
  35526. });
  35527. /**
  35528. * Execute a function that is physics-plugin specific.
  35529. * @param {Function} func the function that will be executed.
  35530. * It accepts two parameters: the physics world and the physics joint.
  35531. */
  35532. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  35533. func(this._physicsPlugin.world, this._physicsJoint);
  35534. };
  35535. return PhysicsJoint;
  35536. }());
  35537. //TODO check if the native joints are the same
  35538. //Joint Types
  35539. PhysicsJoint.DistanceJoint = 0;
  35540. PhysicsJoint.HingeJoint = 1;
  35541. PhysicsJoint.BallAndSocketJoint = 2;
  35542. PhysicsJoint.WheelJoint = 3;
  35543. PhysicsJoint.SliderJoint = 4;
  35544. //OIMO
  35545. PhysicsJoint.PrismaticJoint = 5;
  35546. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  35547. PhysicsJoint.UniversalJoint = 6;
  35548. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  35549. //Cannon
  35550. //Similar to a Ball-Joint. Different in params
  35551. PhysicsJoint.PointToPointJoint = 8;
  35552. //Cannon only at the moment
  35553. PhysicsJoint.SpringJoint = 9;
  35554. PhysicsJoint.LockJoint = 10;
  35555. BABYLON.PhysicsJoint = PhysicsJoint;
  35556. /**
  35557. * A class representing a physics distance joint.
  35558. */
  35559. var DistanceJoint = (function (_super) {
  35560. __extends(DistanceJoint, _super);
  35561. function DistanceJoint(jointData) {
  35562. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  35563. }
  35564. /**
  35565. * Update the predefined distance.
  35566. */
  35567. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  35568. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  35569. };
  35570. return DistanceJoint;
  35571. }(PhysicsJoint));
  35572. BABYLON.DistanceJoint = DistanceJoint;
  35573. var MotorEnabledJoint = (function (_super) {
  35574. __extends(MotorEnabledJoint, _super);
  35575. function MotorEnabledJoint(type, jointData) {
  35576. return _super.call(this, type, jointData) || this;
  35577. }
  35578. /**
  35579. * Set the motor values.
  35580. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35581. * @param {number} force the force to apply
  35582. * @param {number} maxForce max force for this motor.
  35583. */
  35584. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  35585. this._physicsPlugin.setMotor(this, force, maxForce);
  35586. };
  35587. /**
  35588. * Set the motor's limits.
  35589. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35590. */
  35591. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  35592. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  35593. };
  35594. return MotorEnabledJoint;
  35595. }(PhysicsJoint));
  35596. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  35597. /**
  35598. * This class represents a single hinge physics joint
  35599. */
  35600. var HingeJoint = (function (_super) {
  35601. __extends(HingeJoint, _super);
  35602. function HingeJoint(jointData) {
  35603. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  35604. }
  35605. /**
  35606. * Set the motor values.
  35607. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35608. * @param {number} force the force to apply
  35609. * @param {number} maxForce max force for this motor.
  35610. */
  35611. HingeJoint.prototype.setMotor = function (force, maxForce) {
  35612. this._physicsPlugin.setMotor(this, force, maxForce);
  35613. };
  35614. /**
  35615. * Set the motor's limits.
  35616. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35617. */
  35618. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  35619. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  35620. };
  35621. return HingeJoint;
  35622. }(MotorEnabledJoint));
  35623. BABYLON.HingeJoint = HingeJoint;
  35624. /**
  35625. * This class represents a dual hinge physics joint (same as wheel joint)
  35626. */
  35627. var Hinge2Joint = (function (_super) {
  35628. __extends(Hinge2Joint, _super);
  35629. function Hinge2Joint(jointData) {
  35630. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  35631. }
  35632. /**
  35633. * Set the motor values.
  35634. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35635. * @param {number} force the force to apply
  35636. * @param {number} maxForce max force for this motor.
  35637. * @param {motorIndex} the motor's index, 0 or 1.
  35638. */
  35639. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  35640. if (motorIndex === void 0) { motorIndex = 0; }
  35641. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  35642. };
  35643. /**
  35644. * Set the motor limits.
  35645. * Attention, this function is plugin specific. Engines won't react 100% the same.
  35646. * @param {number} upperLimit the upper limit
  35647. * @param {number} lowerLimit lower limit
  35648. * @param {motorIndex} the motor's index, 0 or 1.
  35649. */
  35650. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  35651. if (motorIndex === void 0) { motorIndex = 0; }
  35652. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  35653. };
  35654. return Hinge2Joint;
  35655. }(MotorEnabledJoint));
  35656. BABYLON.Hinge2Joint = Hinge2Joint;
  35657. })(BABYLON || (BABYLON = {}));
  35658. //# sourceMappingURL=babylon.physicsJoint.js.map
  35659. var BABYLON;
  35660. (function (BABYLON) {
  35661. var PhysicsImpostor = (function () {
  35662. function PhysicsImpostor(object, type, _options, _scene) {
  35663. if (_options === void 0) { _options = { mass: 0 }; }
  35664. var _this = this;
  35665. this.object = object;
  35666. this.type = type;
  35667. this._options = _options;
  35668. this._scene = _scene;
  35669. this._bodyUpdateRequired = false;
  35670. this._onBeforePhysicsStepCallbacks = new Array();
  35671. this._onAfterPhysicsStepCallbacks = new Array();
  35672. this._onPhysicsCollideCallbacks = [];
  35673. this._deltaPosition = BABYLON.Vector3.Zero();
  35674. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  35675. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  35676. /**
  35677. * this function is executed by the physics engine.
  35678. */
  35679. this.beforeStep = function () {
  35680. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  35681. //conjugate deltaRotation
  35682. if (_this._deltaRotationConjugated) {
  35683. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  35684. }
  35685. else {
  35686. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  35687. }
  35688. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  35689. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  35690. func(_this);
  35691. });
  35692. };
  35693. /**
  35694. * this function is executed by the physics engine.
  35695. */
  35696. this.afterStep = function () {
  35697. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  35698. func(_this);
  35699. });
  35700. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  35701. _this.object.position.addInPlace(_this._deltaPosition);
  35702. if (_this._deltaRotation) {
  35703. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  35704. }
  35705. };
  35706. /**
  35707. * Legacy collision detection event support
  35708. */
  35709. this.onCollideEvent = null;
  35710. //event and body object due to cannon's event-based architecture.
  35711. this.onCollide = function (e) {
  35712. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  35713. return;
  35714. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  35715. if (otherImpostor) {
  35716. // Legacy collision detection event support
  35717. if (_this.onCollideEvent) {
  35718. _this.onCollideEvent(_this, otherImpostor);
  35719. }
  35720. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  35721. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  35722. }).forEach(function (obj) {
  35723. obj.callback(_this, otherImpostor);
  35724. });
  35725. }
  35726. };
  35727. //sanity check!
  35728. if (!this.object) {
  35729. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  35730. return;
  35731. }
  35732. //legacy support for old syntax.
  35733. if (!this._scene && object.getScene) {
  35734. this._scene = object.getScene();
  35735. }
  35736. this._physicsEngine = this._scene.getPhysicsEngine();
  35737. if (!this._physicsEngine) {
  35738. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  35739. }
  35740. else {
  35741. //set the object's quaternion, if not set
  35742. if (!this.object.rotationQuaternion) {
  35743. if (this.object.rotation) {
  35744. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  35745. }
  35746. else {
  35747. this.object.rotationQuaternion = new BABYLON.Quaternion();
  35748. }
  35749. }
  35750. //default options params
  35751. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  35752. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  35753. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  35754. this._joints = [];
  35755. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  35756. if (!this.object.parent) {
  35757. this._init();
  35758. }
  35759. }
  35760. }
  35761. /**
  35762. * This function will completly initialize this impostor.
  35763. * It will create a new body - but only if this mesh has no parent.
  35764. * If it has, this impostor will not be used other than to define the impostor
  35765. * of the child mesh.
  35766. */
  35767. PhysicsImpostor.prototype._init = function () {
  35768. this._physicsEngine.removeImpostor(this);
  35769. this.physicsBody = null;
  35770. this._parent = this._parent || this._getPhysicsParent();
  35771. if (!this.parent) {
  35772. this._physicsEngine.addImpostor(this);
  35773. }
  35774. };
  35775. PhysicsImpostor.prototype._getPhysicsParent = function () {
  35776. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  35777. var parentMesh = this.object.parent;
  35778. return parentMesh.physicsImpostor;
  35779. }
  35780. return;
  35781. };
  35782. /**
  35783. * Should a new body be generated.
  35784. */
  35785. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  35786. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  35787. };
  35788. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  35789. this.forceUpdate();
  35790. };
  35791. /**
  35792. * Force a regeneration of this or the parent's impostor's body.
  35793. * Use under cautious - This will remove all joints already implemented.
  35794. */
  35795. PhysicsImpostor.prototype.forceUpdate = function () {
  35796. this._init();
  35797. if (this.parent) {
  35798. this.parent.forceUpdate();
  35799. }
  35800. };
  35801. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  35802. /*public get mesh(): AbstractMesh {
  35803. return this._mesh;
  35804. }*/
  35805. /**
  35806. * Gets the body that holds this impostor. Either its own, or its parent.
  35807. */
  35808. get: function () {
  35809. return this._parent ? this._parent.physicsBody : this._physicsBody;
  35810. },
  35811. /**
  35812. * Set the physics body. Used mainly by the physics engine/plugin
  35813. */
  35814. set: function (physicsBody) {
  35815. if (this._physicsBody) {
  35816. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  35817. }
  35818. this._physicsBody = physicsBody;
  35819. this.resetUpdateFlags();
  35820. },
  35821. enumerable: true,
  35822. configurable: true
  35823. });
  35824. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  35825. get: function () {
  35826. return this._parent;
  35827. },
  35828. set: function (value) {
  35829. this._parent = value;
  35830. },
  35831. enumerable: true,
  35832. configurable: true
  35833. });
  35834. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  35835. this._bodyUpdateRequired = false;
  35836. };
  35837. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  35838. if (this.object.getBoundingInfo) {
  35839. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  35840. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  35841. }
  35842. else {
  35843. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  35844. }
  35845. };
  35846. PhysicsImpostor.prototype.getObjectCenter = function () {
  35847. if (this.object.getBoundingInfo) {
  35848. return this.object.getBoundingInfo().boundingBox.center;
  35849. }
  35850. else {
  35851. return this.object.position;
  35852. }
  35853. };
  35854. /**
  35855. * Get a specific parametes from the options parameter.
  35856. */
  35857. PhysicsImpostor.prototype.getParam = function (paramName) {
  35858. return this._options[paramName];
  35859. };
  35860. /**
  35861. * Sets a specific parameter in the options given to the physics plugin
  35862. */
  35863. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  35864. this._options[paramName] = value;
  35865. this._bodyUpdateRequired = true;
  35866. };
  35867. /**
  35868. * Specifically change the body's mass option. Won't recreate the physics body object
  35869. */
  35870. PhysicsImpostor.prototype.setMass = function (mass) {
  35871. if (this.getParam("mass") !== mass) {
  35872. this.setParam("mass", mass);
  35873. }
  35874. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  35875. };
  35876. PhysicsImpostor.prototype.getLinearVelocity = function () {
  35877. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  35878. };
  35879. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  35880. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  35881. };
  35882. PhysicsImpostor.prototype.getAngularVelocity = function () {
  35883. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  35884. };
  35885. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  35886. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  35887. };
  35888. /**
  35889. * Execute a function with the physics plugin native code.
  35890. * Provide a function the will have two variables - the world object and the physics body object.
  35891. */
  35892. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  35893. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  35894. };
  35895. /**
  35896. * Register a function that will be executed before the physics world is stepping forward.
  35897. */
  35898. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  35899. this._onBeforePhysicsStepCallbacks.push(func);
  35900. };
  35901. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  35902. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  35903. if (index > -1) {
  35904. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  35905. }
  35906. else {
  35907. BABYLON.Tools.Warn("Function to remove was not found");
  35908. }
  35909. };
  35910. /**
  35911. * Register a function that will be executed after the physics step
  35912. */
  35913. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  35914. this._onAfterPhysicsStepCallbacks.push(func);
  35915. };
  35916. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  35917. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  35918. if (index > -1) {
  35919. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  35920. }
  35921. else {
  35922. BABYLON.Tools.Warn("Function to remove was not found");
  35923. }
  35924. };
  35925. /**
  35926. * register a function that will be executed when this impostor collides against a different body.
  35927. */
  35928. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  35929. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35930. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  35931. };
  35932. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  35933. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  35934. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  35935. if (index > -1) {
  35936. this._onPhysicsCollideCallbacks.splice(index, 1);
  35937. }
  35938. else {
  35939. BABYLON.Tools.Warn("Function to remove was not found");
  35940. }
  35941. };
  35942. /**
  35943. * Apply a force
  35944. */
  35945. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  35946. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  35947. };
  35948. /**
  35949. * Apply an impulse
  35950. */
  35951. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  35952. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  35953. };
  35954. /**
  35955. * A help function to create a joint.
  35956. */
  35957. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  35958. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  35959. this.addJoint(otherImpostor, joint);
  35960. };
  35961. /**
  35962. * Add a joint to this impostor with a different impostor.
  35963. */
  35964. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  35965. this._joints.push({
  35966. otherImpostor: otherImpostor,
  35967. joint: joint
  35968. });
  35969. this._physicsEngine.addJoint(this, otherImpostor, joint);
  35970. };
  35971. /**
  35972. * Will keep this body still, in a sleep mode.
  35973. */
  35974. PhysicsImpostor.prototype.sleep = function () {
  35975. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  35976. };
  35977. /**
  35978. * Wake the body up.
  35979. */
  35980. PhysicsImpostor.prototype.wakeUp = function () {
  35981. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  35982. };
  35983. PhysicsImpostor.prototype.clone = function (newObject) {
  35984. if (!newObject)
  35985. return null;
  35986. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  35987. };
  35988. PhysicsImpostor.prototype.dispose = function () {
  35989. var _this = this;
  35990. //no dispose if no physics engine is available.
  35991. if (!this._physicsEngine) {
  35992. return;
  35993. }
  35994. this._joints.forEach(function (j) {
  35995. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  35996. });
  35997. //dispose the physics body
  35998. this._physicsEngine.removeImpostor(this);
  35999. if (this.parent) {
  36000. this.parent.forceUpdate();
  36001. }
  36002. else {
  36003. }
  36004. };
  36005. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  36006. this._deltaPosition.copyFrom(position);
  36007. };
  36008. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  36009. if (!this._deltaRotation) {
  36010. this._deltaRotation = new BABYLON.Quaternion();
  36011. }
  36012. this._deltaRotation.copyFrom(rotation);
  36013. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  36014. };
  36015. return PhysicsImpostor;
  36016. }());
  36017. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  36018. //Impostor types
  36019. PhysicsImpostor.NoImpostor = 0;
  36020. PhysicsImpostor.SphereImpostor = 1;
  36021. PhysicsImpostor.BoxImpostor = 2;
  36022. PhysicsImpostor.PlaneImpostor = 3;
  36023. PhysicsImpostor.MeshImpostor = 4;
  36024. PhysicsImpostor.CylinderImpostor = 7;
  36025. PhysicsImpostor.ParticleImpostor = 8;
  36026. PhysicsImpostor.HeightmapImpostor = 9;
  36027. BABYLON.PhysicsImpostor = PhysicsImpostor;
  36028. })(BABYLON || (BABYLON = {}));
  36029. //# sourceMappingURL=babylon.physicsImpostor.js.map
  36030. var BABYLON;
  36031. (function (BABYLON) {
  36032. var PhysicsEngine = (function () {
  36033. function PhysicsEngine(gravity, _physicsPlugin) {
  36034. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  36035. this._physicsPlugin = _physicsPlugin;
  36036. //new methods and parameters
  36037. this._impostors = [];
  36038. this._joints = [];
  36039. if (!this._physicsPlugin.isSupported()) {
  36040. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  36041. + "Please make sure it is included.");
  36042. }
  36043. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  36044. this.setGravity(gravity);
  36045. this.setTimeStep();
  36046. }
  36047. PhysicsEngine.prototype.setGravity = function (gravity) {
  36048. this.gravity = gravity;
  36049. this._physicsPlugin.setGravity(this.gravity);
  36050. };
  36051. /**
  36052. * Set the time step of the physics engine.
  36053. * default is 1/60.
  36054. * To slow it down, enter 1/600 for example.
  36055. * To speed it up, 1/30
  36056. * @param {number} newTimeStep the new timestep to apply to this world.
  36057. */
  36058. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  36059. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  36060. this._physicsPlugin.setTimeStep(newTimeStep);
  36061. };
  36062. PhysicsEngine.prototype.dispose = function () {
  36063. this._impostors.forEach(function (impostor) {
  36064. impostor.dispose();
  36065. });
  36066. this._physicsPlugin.dispose();
  36067. };
  36068. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  36069. return this._physicsPlugin.name;
  36070. };
  36071. /**
  36072. * Adding a new impostor for the impostor tracking.
  36073. * This will be done by the impostor itself.
  36074. * @param {PhysicsImpostor} impostor the impostor to add
  36075. */
  36076. PhysicsEngine.prototype.addImpostor = function (impostor) {
  36077. impostor.uniqueId = this._impostors.push(impostor);
  36078. //if no parent, generate the body
  36079. if (!impostor.parent) {
  36080. this._physicsPlugin.generatePhysicsBody(impostor);
  36081. }
  36082. };
  36083. /**
  36084. * Remove an impostor from the engine.
  36085. * This impostor and its mesh will not longer be updated by the physics engine.
  36086. * @param {PhysicsImpostor} impostor the impostor to remove
  36087. */
  36088. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  36089. var index = this._impostors.indexOf(impostor);
  36090. if (index > -1) {
  36091. var removed = this._impostors.splice(index, 1);
  36092. //Is it needed?
  36093. if (removed.length) {
  36094. //this will also remove it from the world.
  36095. removed[0].physicsBody = null;
  36096. }
  36097. }
  36098. };
  36099. /**
  36100. * Add a joint to the physics engine
  36101. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  36102. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  36103. * @param {PhysicsJoint} the joint that will connect both impostors.
  36104. */
  36105. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  36106. var impostorJoint = {
  36107. mainImpostor: mainImpostor,
  36108. connectedImpostor: connectedImpostor,
  36109. joint: joint
  36110. };
  36111. joint.physicsPlugin = this._physicsPlugin;
  36112. this._joints.push(impostorJoint);
  36113. this._physicsPlugin.generateJoint(impostorJoint);
  36114. };
  36115. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  36116. var matchingJoints = this._joints.filter(function (impostorJoint) {
  36117. return (impostorJoint.connectedImpostor === connectedImpostor
  36118. && impostorJoint.joint === joint
  36119. && impostorJoint.mainImpostor === mainImpostor);
  36120. });
  36121. if (matchingJoints.length) {
  36122. this._physicsPlugin.removeJoint(matchingJoints[0]);
  36123. }
  36124. };
  36125. /**
  36126. * Called by the scene. no need to call it.
  36127. */
  36128. PhysicsEngine.prototype._step = function (delta) {
  36129. var _this = this;
  36130. //check if any mesh has no body / requires an update
  36131. this._impostors.forEach(function (impostor) {
  36132. if (impostor.isBodyInitRequired()) {
  36133. _this._physicsPlugin.generatePhysicsBody(impostor);
  36134. }
  36135. });
  36136. if (delta > 0.1) {
  36137. delta = 0.1;
  36138. }
  36139. else if (delta <= 0) {
  36140. delta = 1.0 / 60.0;
  36141. }
  36142. this._physicsPlugin.executeStep(delta, this._impostors);
  36143. };
  36144. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  36145. return this._physicsPlugin;
  36146. };
  36147. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  36148. for (var i = 0; i < this._impostors.length; ++i) {
  36149. if (this._impostors[i].object === object) {
  36150. return this._impostors[i];
  36151. }
  36152. }
  36153. };
  36154. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  36155. for (var i = 0; i < this._impostors.length; ++i) {
  36156. if (this._impostors[i].physicsBody === body) {
  36157. return this._impostors[i];
  36158. }
  36159. }
  36160. };
  36161. return PhysicsEngine;
  36162. }());
  36163. // Statics
  36164. PhysicsEngine.Epsilon = 0.001;
  36165. BABYLON.PhysicsEngine = PhysicsEngine;
  36166. })(BABYLON || (BABYLON = {}));
  36167. //# sourceMappingURL=babylon.physicsEngine.js.map
  36168. var BABYLON;
  36169. (function (BABYLON) {
  36170. var VertexData = (function () {
  36171. function VertexData() {
  36172. }
  36173. VertexData.prototype.set = function (data, kind) {
  36174. switch (kind) {
  36175. case BABYLON.VertexBuffer.PositionKind:
  36176. this.positions = data;
  36177. break;
  36178. case BABYLON.VertexBuffer.NormalKind:
  36179. this.normals = data;
  36180. break;
  36181. case BABYLON.VertexBuffer.UVKind:
  36182. this.uvs = data;
  36183. break;
  36184. case BABYLON.VertexBuffer.UV2Kind:
  36185. this.uvs2 = data;
  36186. break;
  36187. case BABYLON.VertexBuffer.UV3Kind:
  36188. this.uvs3 = data;
  36189. break;
  36190. case BABYLON.VertexBuffer.UV4Kind:
  36191. this.uvs4 = data;
  36192. break;
  36193. case BABYLON.VertexBuffer.UV5Kind:
  36194. this.uvs5 = data;
  36195. break;
  36196. case BABYLON.VertexBuffer.UV6Kind:
  36197. this.uvs6 = data;
  36198. break;
  36199. case BABYLON.VertexBuffer.ColorKind:
  36200. this.colors = data;
  36201. break;
  36202. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36203. this.matricesIndices = data;
  36204. break;
  36205. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36206. this.matricesWeights = data;
  36207. break;
  36208. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36209. this.matricesIndicesExtra = data;
  36210. break;
  36211. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36212. this.matricesWeightsExtra = data;
  36213. break;
  36214. }
  36215. };
  36216. /**
  36217. * Associates the vertexData to the passed Mesh.
  36218. * Sets it as updatable or not (default `false`).
  36219. * Returns the VertexData.
  36220. */
  36221. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36222. this._applyTo(mesh, updatable);
  36223. return this;
  36224. };
  36225. /**
  36226. * Associates the vertexData to the passed Geometry.
  36227. * Sets it as updatable or not (default `false`).
  36228. * Returns the VertexData.
  36229. */
  36230. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36231. this._applyTo(geometry, updatable);
  36232. return this;
  36233. };
  36234. /**
  36235. * Updates the associated mesh.
  36236. * Returns the VertexData.
  36237. */
  36238. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36239. this._update(mesh);
  36240. return this;
  36241. };
  36242. /**
  36243. * Updates the associated geometry.
  36244. * Returns the VertexData.
  36245. */
  36246. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36247. this._update(geometry);
  36248. return this;
  36249. };
  36250. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36251. if (this.positions) {
  36252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36253. }
  36254. if (this.normals) {
  36255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36256. }
  36257. if (this.uvs) {
  36258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36259. }
  36260. if (this.uvs2) {
  36261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36262. }
  36263. if (this.uvs3) {
  36264. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36265. }
  36266. if (this.uvs4) {
  36267. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36268. }
  36269. if (this.uvs5) {
  36270. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36271. }
  36272. if (this.uvs6) {
  36273. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36274. }
  36275. if (this.colors) {
  36276. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36277. }
  36278. if (this.matricesIndices) {
  36279. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36280. }
  36281. if (this.matricesWeights) {
  36282. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36283. }
  36284. if (this.matricesIndicesExtra) {
  36285. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36286. }
  36287. if (this.matricesWeightsExtra) {
  36288. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36289. }
  36290. if (this.indices) {
  36291. meshOrGeometry.setIndices(this.indices);
  36292. }
  36293. return this;
  36294. };
  36295. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36296. if (this.positions) {
  36297. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36298. }
  36299. if (this.normals) {
  36300. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36301. }
  36302. if (this.uvs) {
  36303. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36304. }
  36305. if (this.uvs2) {
  36306. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36307. }
  36308. if (this.uvs3) {
  36309. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36310. }
  36311. if (this.uvs4) {
  36312. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36313. }
  36314. if (this.uvs5) {
  36315. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36316. }
  36317. if (this.uvs6) {
  36318. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36319. }
  36320. if (this.colors) {
  36321. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36322. }
  36323. if (this.matricesIndices) {
  36324. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36325. }
  36326. if (this.matricesWeights) {
  36327. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36328. }
  36329. if (this.matricesIndicesExtra) {
  36330. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36331. }
  36332. if (this.matricesWeightsExtra) {
  36333. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36334. }
  36335. if (this.indices) {
  36336. meshOrGeometry.setIndices(this.indices);
  36337. }
  36338. return this;
  36339. };
  36340. /**
  36341. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  36342. * Returns the VertexData.
  36343. */
  36344. VertexData.prototype.transform = function (matrix) {
  36345. var transformed = BABYLON.Vector3.Zero();
  36346. var index;
  36347. if (this.positions) {
  36348. var position = BABYLON.Vector3.Zero();
  36349. for (index = 0; index < this.positions.length; index += 3) {
  36350. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36351. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36352. this.positions[index] = transformed.x;
  36353. this.positions[index + 1] = transformed.y;
  36354. this.positions[index + 2] = transformed.z;
  36355. }
  36356. }
  36357. if (this.normals) {
  36358. var normal = BABYLON.Vector3.Zero();
  36359. for (index = 0; index < this.normals.length; index += 3) {
  36360. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36361. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36362. this.normals[index] = transformed.x;
  36363. this.normals[index + 1] = transformed.y;
  36364. this.normals[index + 2] = transformed.z;
  36365. }
  36366. }
  36367. return this;
  36368. };
  36369. /**
  36370. * Merges the passed VertexData into the current one.
  36371. * Returns the modified VertexData.
  36372. */
  36373. VertexData.prototype.merge = function (other) {
  36374. if (other.indices) {
  36375. if (!this.indices) {
  36376. this.indices = [];
  36377. }
  36378. var offset = this.positions ? this.positions.length / 3 : 0;
  36379. for (var index = 0; index < other.indices.length; index++) {
  36380. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36381. this.indices.push(other.indices[index] + offset);
  36382. }
  36383. }
  36384. this.positions = this._mergeElement(this.positions, other.positions);
  36385. this.normals = this._mergeElement(this.normals, other.normals);
  36386. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36387. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36388. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36389. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36390. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36391. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36392. this.colors = this._mergeElement(this.colors, other.colors);
  36393. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36394. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36395. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36396. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36397. return this;
  36398. };
  36399. VertexData.prototype._mergeElement = function (source, other) {
  36400. if (!other)
  36401. return source;
  36402. if (!source)
  36403. return other;
  36404. var len = other.length + source.length;
  36405. var isSrcTypedArray = source instanceof Float32Array;
  36406. var isOthTypedArray = other instanceof Float32Array;
  36407. // use non-loop method when the source is Float32Array
  36408. if (isSrcTypedArray) {
  36409. var ret32 = new Float32Array(len);
  36410. ret32.set(source);
  36411. ret32.set(other, source.length);
  36412. return ret32;
  36413. }
  36414. else if (!isOthTypedArray) {
  36415. return source.concat(other);
  36416. }
  36417. else {
  36418. var ret = source.slice(0); // copy source to a separate array
  36419. for (var i = 0, len = other.length; i < len; i++) {
  36420. ret.push(other[i]);
  36421. }
  36422. return ret;
  36423. }
  36424. };
  36425. /**
  36426. * Serializes the VertexData.
  36427. * Returns a serialized object.
  36428. */
  36429. VertexData.prototype.serialize = function () {
  36430. var serializationObject = this.serialize();
  36431. if (this.positions) {
  36432. serializationObject.positions = this.positions;
  36433. }
  36434. if (this.normals) {
  36435. serializationObject.normals = this.normals;
  36436. }
  36437. if (this.uvs) {
  36438. serializationObject.uvs = this.uvs;
  36439. }
  36440. if (this.uvs2) {
  36441. serializationObject.uvs2 = this.uvs2;
  36442. }
  36443. if (this.uvs3) {
  36444. serializationObject.uvs3 = this.uvs3;
  36445. }
  36446. if (this.uvs4) {
  36447. serializationObject.uvs4 = this.uvs4;
  36448. }
  36449. if (this.uvs5) {
  36450. serializationObject.uvs5 = this.uvs5;
  36451. }
  36452. if (this.uvs6) {
  36453. serializationObject.uvs6 = this.uvs6;
  36454. }
  36455. if (this.colors) {
  36456. serializationObject.colors = this.colors;
  36457. }
  36458. if (this.matricesIndices) {
  36459. serializationObject.matricesIndices = this.matricesIndices;
  36460. serializationObject.matricesIndices._isExpanded = true;
  36461. }
  36462. if (this.matricesWeights) {
  36463. serializationObject.matricesWeights = this.matricesWeights;
  36464. }
  36465. if (this.matricesIndicesExtra) {
  36466. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36467. serializationObject.matricesIndicesExtra._isExpanded = true;
  36468. }
  36469. if (this.matricesWeightsExtra) {
  36470. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36471. }
  36472. serializationObject.indices = this.indices;
  36473. return serializationObject;
  36474. };
  36475. // Statics
  36476. /**
  36477. * Returns the object VertexData associated to the passed mesh.
  36478. */
  36479. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  36480. return VertexData._ExtractFrom(mesh, copyWhenShared);
  36481. };
  36482. /**
  36483. * Returns the object VertexData associated to the passed geometry.
  36484. */
  36485. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  36486. return VertexData._ExtractFrom(geometry, copyWhenShared);
  36487. };
  36488. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  36489. var result = new VertexData();
  36490. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36491. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  36492. }
  36493. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36494. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  36495. }
  36496. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36497. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  36498. }
  36499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36500. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  36501. }
  36502. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36503. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  36504. }
  36505. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36506. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  36507. }
  36508. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36509. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  36510. }
  36511. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36512. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  36513. }
  36514. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36515. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  36516. }
  36517. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36518. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  36519. }
  36520. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36521. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  36522. }
  36523. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36524. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  36525. }
  36526. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36527. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  36528. }
  36529. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36530. return result;
  36531. };
  36532. /**
  36533. * Creates the vertexData of the Ribbon.
  36534. */
  36535. VertexData.CreateRibbon = function (options) {
  36536. var pathArray = options.pathArray;
  36537. var closeArray = options.closeArray || false;
  36538. var closePath = options.closePath || false;
  36539. var invertUV = options.invertUV || false;
  36540. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36541. var offset = options.offset || defaultOffset;
  36542. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36543. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36544. var positions = [];
  36545. var indices = [];
  36546. var normals = [];
  36547. var uvs = [];
  36548. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36549. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36550. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36551. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36552. var minlg; // minimal length among all paths from pathArray
  36553. var lg = []; // array of path lengths : nb of vertex per path
  36554. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36555. var p; // path iterator
  36556. var i; // point iterator
  36557. var j; // point iterator
  36558. // if single path in pathArray
  36559. if (pathArray.length < 2) {
  36560. var ar1 = [];
  36561. var ar2 = [];
  36562. for (i = 0; i < pathArray[0].length - offset; i++) {
  36563. ar1.push(pathArray[0][i]);
  36564. ar2.push(pathArray[0][i + offset]);
  36565. }
  36566. pathArray = [ar1, ar2];
  36567. }
  36568. // positions and horizontal distances (u)
  36569. var idc = 0;
  36570. var closePathCorr = (closePath) ? 1 : 0;
  36571. var path;
  36572. var l;
  36573. minlg = pathArray[0].length;
  36574. var vectlg;
  36575. var dist;
  36576. for (p = 0; p < pathArray.length; p++) {
  36577. uTotalDistance[p] = 0;
  36578. us[p] = [0];
  36579. path = pathArray[p];
  36580. l = path.length;
  36581. minlg = (minlg < l) ? minlg : l;
  36582. j = 0;
  36583. while (j < l) {
  36584. positions.push(path[j].x, path[j].y, path[j].z);
  36585. if (j > 0) {
  36586. vectlg = path[j].subtract(path[j - 1]).length();
  36587. dist = vectlg + uTotalDistance[p];
  36588. us[p].push(dist);
  36589. uTotalDistance[p] = dist;
  36590. }
  36591. j++;
  36592. }
  36593. if (closePath) {
  36594. j--;
  36595. positions.push(path[0].x, path[0].y, path[0].z);
  36596. vectlg = path[j].subtract(path[0]).length();
  36597. dist = vectlg + uTotalDistance[p];
  36598. us[p].push(dist);
  36599. uTotalDistance[p] = dist;
  36600. }
  36601. lg[p] = l + closePathCorr;
  36602. idx[p] = idc;
  36603. idc += (l + closePathCorr);
  36604. }
  36605. // vertical distances (v)
  36606. var path1;
  36607. var path2;
  36608. var vertex1;
  36609. var vertex2;
  36610. for (i = 0; i < minlg + closePathCorr; i++) {
  36611. vTotalDistance[i] = 0;
  36612. vs[i] = [0];
  36613. for (p = 0; p < pathArray.length - 1; p++) {
  36614. path1 = pathArray[p];
  36615. path2 = pathArray[p + 1];
  36616. if (i === minlg) {
  36617. vertex1 = path1[0];
  36618. vertex2 = path2[0];
  36619. }
  36620. else {
  36621. vertex1 = path1[i];
  36622. vertex2 = path2[i];
  36623. }
  36624. vectlg = vertex2.subtract(vertex1).length();
  36625. dist = vectlg + vTotalDistance[i];
  36626. vs[i].push(dist);
  36627. vTotalDistance[i] = dist;
  36628. }
  36629. if (closeArray) {
  36630. path1 = pathArray[p];
  36631. path2 = pathArray[0];
  36632. if (i === minlg) {
  36633. vertex2 = path2[0];
  36634. }
  36635. vectlg = vertex2.subtract(vertex1).length();
  36636. dist = vectlg + vTotalDistance[i];
  36637. vTotalDistance[i] = dist;
  36638. }
  36639. }
  36640. // uvs
  36641. var u;
  36642. var v;
  36643. for (p = 0; p < pathArray.length; p++) {
  36644. for (i = 0; i < minlg + closePathCorr; i++) {
  36645. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36646. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36647. if (invertUV) {
  36648. uvs.push(v, u);
  36649. }
  36650. else {
  36651. uvs.push(u, v);
  36652. }
  36653. }
  36654. }
  36655. // indices
  36656. p = 0; // path index
  36657. var pi = 0; // positions array index
  36658. var l1 = lg[p] - 1; // path1 length
  36659. var l2 = lg[p + 1] - 1; // path2 length
  36660. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36661. var shft = idx[1] - idx[0]; // shift
  36662. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36663. while (pi <= min && p < path1nb) {
  36664. // 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
  36665. indices.push(pi, pi + shft, pi + 1);
  36666. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36667. pi += 1;
  36668. if (pi === min) {
  36669. p++;
  36670. if (p === lg.length - 1) {
  36671. shft = idx[0] - idx[p];
  36672. l1 = lg[p] - 1;
  36673. l2 = lg[0] - 1;
  36674. }
  36675. else {
  36676. shft = idx[p + 1] - idx[p];
  36677. l1 = lg[p] - 1;
  36678. l2 = lg[p + 1] - 1;
  36679. }
  36680. pi = idx[p];
  36681. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36682. }
  36683. }
  36684. // normals
  36685. VertexData.ComputeNormals(positions, indices, normals);
  36686. if (closePath) {
  36687. var indexFirst = 0;
  36688. var indexLast = 0;
  36689. for (p = 0; p < pathArray.length; p++) {
  36690. indexFirst = idx[p] * 3;
  36691. if (p + 1 < pathArray.length) {
  36692. indexLast = (idx[p + 1] - 1) * 3;
  36693. }
  36694. else {
  36695. indexLast = normals.length - 3;
  36696. }
  36697. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36698. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36699. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36700. normals[indexLast] = normals[indexFirst];
  36701. normals[indexLast + 1] = normals[indexFirst + 1];
  36702. normals[indexLast + 2] = normals[indexFirst + 2];
  36703. }
  36704. }
  36705. // sides
  36706. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36707. // Result
  36708. var vertexData = new VertexData();
  36709. vertexData.indices = indices;
  36710. vertexData.positions = positions;
  36711. vertexData.normals = normals;
  36712. vertexData.uvs = uvs;
  36713. if (closePath) {
  36714. vertexData._idx = idx;
  36715. }
  36716. return vertexData;
  36717. };
  36718. /**
  36719. * Creates the VertexData of the Box.
  36720. */
  36721. VertexData.CreateBox = function (options) {
  36722. var normalsSource = [
  36723. new BABYLON.Vector3(0, 0, 1),
  36724. new BABYLON.Vector3(0, 0, -1),
  36725. new BABYLON.Vector3(1, 0, 0),
  36726. new BABYLON.Vector3(-1, 0, 0),
  36727. new BABYLON.Vector3(0, 1, 0),
  36728. new BABYLON.Vector3(0, -1, 0)
  36729. ];
  36730. var indices = [];
  36731. var positions = [];
  36732. var normals = [];
  36733. var uvs = [];
  36734. var width = options.width || options.size || 1;
  36735. var height = options.height || options.size || 1;
  36736. var depth = options.depth || options.size || 1;
  36737. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36738. var faceUV = options.faceUV || new Array(6);
  36739. var faceColors = options.faceColors;
  36740. var colors = [];
  36741. // default face colors and UV if undefined
  36742. for (var f = 0; f < 6; f++) {
  36743. if (faceUV[f] === undefined) {
  36744. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36745. }
  36746. if (faceColors && faceColors[f] === undefined) {
  36747. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36748. }
  36749. }
  36750. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36751. // Create each face in turn.
  36752. for (var index = 0; index < normalsSource.length; index++) {
  36753. var normal = normalsSource[index];
  36754. // Get two vectors perpendicular to the face normal and to each other.
  36755. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36756. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36757. // Six indices (two triangles) per face.
  36758. var verticesLength = positions.length / 3;
  36759. indices.push(verticesLength);
  36760. indices.push(verticesLength + 1);
  36761. indices.push(verticesLength + 2);
  36762. indices.push(verticesLength);
  36763. indices.push(verticesLength + 2);
  36764. indices.push(verticesLength + 3);
  36765. // Four vertices per face.
  36766. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36767. positions.push(vertex.x, vertex.y, vertex.z);
  36768. normals.push(normal.x, normal.y, normal.z);
  36769. uvs.push(faceUV[index].z, faceUV[index].w);
  36770. if (faceColors) {
  36771. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36772. }
  36773. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36774. positions.push(vertex.x, vertex.y, vertex.z);
  36775. normals.push(normal.x, normal.y, normal.z);
  36776. uvs.push(faceUV[index].x, faceUV[index].w);
  36777. if (faceColors) {
  36778. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36779. }
  36780. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36781. positions.push(vertex.x, vertex.y, vertex.z);
  36782. normals.push(normal.x, normal.y, normal.z);
  36783. uvs.push(faceUV[index].x, faceUV[index].y);
  36784. if (faceColors) {
  36785. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36786. }
  36787. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36788. positions.push(vertex.x, vertex.y, vertex.z);
  36789. normals.push(normal.x, normal.y, normal.z);
  36790. uvs.push(faceUV[index].z, faceUV[index].y);
  36791. if (faceColors) {
  36792. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36793. }
  36794. }
  36795. // sides
  36796. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36797. // Result
  36798. var vertexData = new VertexData();
  36799. vertexData.indices = indices;
  36800. vertexData.positions = positions;
  36801. vertexData.normals = normals;
  36802. vertexData.uvs = uvs;
  36803. if (faceColors) {
  36804. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36805. vertexData.colors = totalColors;
  36806. }
  36807. return vertexData;
  36808. };
  36809. /**
  36810. * Creates the VertexData of the Sphere.
  36811. */
  36812. VertexData.CreateSphere = function (options) {
  36813. var segments = options.segments || 32;
  36814. var diameterX = options.diameterX || options.diameter || 1;
  36815. var diameterY = options.diameterY || options.diameter || 1;
  36816. var diameterZ = options.diameterZ || options.diameter || 1;
  36817. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36818. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36819. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36820. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36821. var totalZRotationSteps = 2 + segments;
  36822. var totalYRotationSteps = 2 * totalZRotationSteps;
  36823. var indices = [];
  36824. var positions = [];
  36825. var normals = [];
  36826. var uvs = [];
  36827. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36828. var normalizedZ = zRotationStep / totalZRotationSteps;
  36829. var angleZ = normalizedZ * Math.PI * slice;
  36830. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36831. var normalizedY = yRotationStep / totalYRotationSteps;
  36832. var angleY = normalizedY * Math.PI * 2 * arc;
  36833. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36834. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36835. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36836. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36837. var vertex = complete.multiply(radius);
  36838. var normal = complete.divide(radius).normalize();
  36839. positions.push(vertex.x, vertex.y, vertex.z);
  36840. normals.push(normal.x, normal.y, normal.z);
  36841. uvs.push(normalizedY, normalizedZ);
  36842. }
  36843. if (zRotationStep > 0) {
  36844. var verticesCount = positions.length / 3;
  36845. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36846. indices.push((firstIndex));
  36847. indices.push((firstIndex + 1));
  36848. indices.push(firstIndex + totalYRotationSteps + 1);
  36849. indices.push((firstIndex + totalYRotationSteps + 1));
  36850. indices.push((firstIndex + 1));
  36851. indices.push((firstIndex + totalYRotationSteps + 2));
  36852. }
  36853. }
  36854. }
  36855. // Sides
  36856. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  36857. // Result
  36858. var vertexData = new VertexData();
  36859. vertexData.indices = indices;
  36860. vertexData.positions = positions;
  36861. vertexData.normals = normals;
  36862. vertexData.uvs = uvs;
  36863. return vertexData;
  36864. };
  36865. /**
  36866. * Creates the VertexData of the Cylinder or Cone.
  36867. */
  36868. VertexData.CreateCylinder = function (options) {
  36869. var height = options.height || 2;
  36870. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36871. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36872. var tessellation = options.tessellation || 24;
  36873. var subdivisions = options.subdivisions || 1;
  36874. var hasRings = options.hasRings;
  36875. var enclose = options.enclose;
  36876. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36877. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36878. var faceUV = options.faceUV || new Array(3);
  36879. var faceColors = options.faceColors;
  36880. // default face colors and UV if undefined
  36881. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36882. var ringNb = (hasRings) ? subdivisions : 1;
  36883. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36884. var f;
  36885. for (f = 0; f < surfaceNb; f++) {
  36886. if (faceColors && faceColors[f] === undefined) {
  36887. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36888. }
  36889. }
  36890. for (f = 0; f < surfaceNb; f++) {
  36891. if (faceUV && faceUV[f] === undefined) {
  36892. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36893. }
  36894. }
  36895. var indices = [];
  36896. var positions = [];
  36897. var normals = [];
  36898. var uvs = [];
  36899. var colors = [];
  36900. var angle_step = Math.PI * 2 * arc / tessellation;
  36901. var angle;
  36902. var h;
  36903. var radius;
  36904. var tan = (diameterBottom - diameterTop) / 2 / height;
  36905. var ringVertex = BABYLON.Vector3.Zero();
  36906. var ringNormal = BABYLON.Vector3.Zero();
  36907. var ringFirstVertex = BABYLON.Vector3.Zero();
  36908. var ringFirstNormal = BABYLON.Vector3.Zero();
  36909. var quadNormal = BABYLON.Vector3.Zero();
  36910. var Y = BABYLON.Axis.Y;
  36911. // positions, normals, uvs
  36912. var i;
  36913. var j;
  36914. var r;
  36915. var ringIdx = 1;
  36916. var s = 1; // surface index
  36917. var cs = 0;
  36918. var v = 0;
  36919. for (i = 0; i <= subdivisions; i++) {
  36920. h = i / subdivisions;
  36921. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36922. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36923. for (r = 0; r < ringIdx; r++) {
  36924. if (hasRings) {
  36925. s += r;
  36926. }
  36927. if (enclose) {
  36928. s += 2 * r;
  36929. }
  36930. for (j = 0; j <= tessellation; j++) {
  36931. angle = j * angle_step;
  36932. // position
  36933. ringVertex.x = Math.cos(-angle) * radius;
  36934. ringVertex.y = -height / 2 + h * height;
  36935. ringVertex.z = Math.sin(-angle) * radius;
  36936. // normal
  36937. if (diameterTop === 0 && i === subdivisions) {
  36938. // if no top cap, reuse former normals
  36939. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36940. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36941. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36942. }
  36943. else {
  36944. ringNormal.x = ringVertex.x;
  36945. ringNormal.z = ringVertex.z;
  36946. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36947. ringNormal.normalize();
  36948. }
  36949. // keep first ring vertex values for enclose
  36950. if (j === 0) {
  36951. ringFirstVertex.copyFrom(ringVertex);
  36952. ringFirstNormal.copyFrom(ringNormal);
  36953. }
  36954. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36955. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36956. if (hasRings) {
  36957. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36958. }
  36959. else {
  36960. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36961. }
  36962. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36963. if (faceColors) {
  36964. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36965. }
  36966. }
  36967. // if enclose, add four vertices and their dedicated normals
  36968. if (arc !== 1 && enclose) {
  36969. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36970. positions.push(0, ringVertex.y, 0);
  36971. positions.push(0, ringVertex.y, 0);
  36972. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36973. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36974. quadNormal.normalize();
  36975. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36976. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36977. quadNormal.normalize();
  36978. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36979. if (hasRings) {
  36980. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36981. }
  36982. else {
  36983. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36984. }
  36985. uvs.push(faceUV[s + 1].x, v);
  36986. uvs.push(faceUV[s + 1].z, v);
  36987. if (hasRings) {
  36988. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36989. }
  36990. else {
  36991. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36992. }
  36993. uvs.push(faceUV[s + 2].x, v);
  36994. uvs.push(faceUV[s + 2].z, v);
  36995. if (faceColors) {
  36996. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36997. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36998. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36999. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37000. }
  37001. }
  37002. if (cs !== s) {
  37003. cs = s;
  37004. }
  37005. }
  37006. }
  37007. // indices
  37008. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37009. var s;
  37010. i = 0;
  37011. for (s = 0; s < subdivisions; s++) {
  37012. for (j = 0; j < tessellation; j++) {
  37013. var i0 = i * (e + 1) + j;
  37014. var i1 = (i + 1) * (e + 1) + j;
  37015. var i2 = i * (e + 1) + (j + 1);
  37016. var i3 = (i + 1) * (e + 1) + (j + 1);
  37017. indices.push(i0, i1, i2);
  37018. indices.push(i3, i2, i1);
  37019. }
  37020. if (arc !== 1 && enclose) {
  37021. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37022. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37023. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37024. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37025. }
  37026. i = (hasRings) ? (i + 2) : (i + 1);
  37027. }
  37028. // Caps
  37029. var createCylinderCap = function (isTop) {
  37030. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37031. if (radius === 0) {
  37032. return;
  37033. }
  37034. // Cap positions, normals & uvs
  37035. var angle;
  37036. var circleVector;
  37037. var i;
  37038. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37039. var c;
  37040. if (faceColors) {
  37041. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37042. }
  37043. // cap center
  37044. var vbase = positions.length / 3;
  37045. var offset = isTop ? height / 2 : -height / 2;
  37046. var center = new BABYLON.Vector3(0, offset, 0);
  37047. positions.push(center.x, center.y, center.z);
  37048. normals.push(0, isTop ? 1 : -1, 0);
  37049. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37050. if (faceColors) {
  37051. colors.push(c.r, c.g, c.b, c.a);
  37052. }
  37053. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37054. for (i = 0; i <= tessellation; i++) {
  37055. angle = Math.PI * 2 * i * arc / tessellation;
  37056. var cos = Math.cos(-angle);
  37057. var sin = Math.sin(-angle);
  37058. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37059. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37060. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37061. normals.push(0, isTop ? 1 : -1, 0);
  37062. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37063. if (faceColors) {
  37064. colors.push(c.r, c.g, c.b, c.a);
  37065. }
  37066. }
  37067. // Cap indices
  37068. for (i = 0; i < tessellation; i++) {
  37069. if (!isTop) {
  37070. indices.push(vbase);
  37071. indices.push(vbase + (i + 1));
  37072. indices.push(vbase + (i + 2));
  37073. }
  37074. else {
  37075. indices.push(vbase);
  37076. indices.push(vbase + (i + 2));
  37077. indices.push(vbase + (i + 1));
  37078. }
  37079. }
  37080. };
  37081. // add caps to geometry
  37082. createCylinderCap(false);
  37083. createCylinderCap(true);
  37084. // Sides
  37085. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37086. var vertexData = new VertexData();
  37087. vertexData.indices = indices;
  37088. vertexData.positions = positions;
  37089. vertexData.normals = normals;
  37090. vertexData.uvs = uvs;
  37091. if (faceColors) {
  37092. vertexData.colors = colors;
  37093. }
  37094. return vertexData;
  37095. };
  37096. /**
  37097. * Creates the VertexData of the Torus.
  37098. */
  37099. VertexData.CreateTorus = function (options) {
  37100. var indices = [];
  37101. var positions = [];
  37102. var normals = [];
  37103. var uvs = [];
  37104. var diameter = options.diameter || 1;
  37105. var thickness = options.thickness || 0.5;
  37106. var tessellation = options.tessellation || 16;
  37107. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37108. var stride = tessellation + 1;
  37109. for (var i = 0; i <= tessellation; i++) {
  37110. var u = i / tessellation;
  37111. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37112. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37113. for (var j = 0; j <= tessellation; j++) {
  37114. var v = 1 - j / tessellation;
  37115. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37116. var dx = Math.cos(innerAngle);
  37117. var dy = Math.sin(innerAngle);
  37118. // Create a vertex.
  37119. var normal = new BABYLON.Vector3(dx, dy, 0);
  37120. var position = normal.scale(thickness / 2);
  37121. var textureCoordinate = new BABYLON.Vector2(u, v);
  37122. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37123. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37124. positions.push(position.x, position.y, position.z);
  37125. normals.push(normal.x, normal.y, normal.z);
  37126. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37127. // And create indices for two triangles.
  37128. var nextI = (i + 1) % stride;
  37129. var nextJ = (j + 1) % stride;
  37130. indices.push(i * stride + j);
  37131. indices.push(i * stride + nextJ);
  37132. indices.push(nextI * stride + j);
  37133. indices.push(i * stride + nextJ);
  37134. indices.push(nextI * stride + nextJ);
  37135. indices.push(nextI * stride + j);
  37136. }
  37137. }
  37138. // Sides
  37139. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37140. // Result
  37141. var vertexData = new VertexData();
  37142. vertexData.indices = indices;
  37143. vertexData.positions = positions;
  37144. vertexData.normals = normals;
  37145. vertexData.uvs = uvs;
  37146. return vertexData;
  37147. };
  37148. /**
  37149. * Creates the VertexData of the LineSystem.
  37150. */
  37151. VertexData.CreateLineSystem = function (options) {
  37152. var indices = [];
  37153. var positions = [];
  37154. var lines = options.lines;
  37155. var idx = 0;
  37156. for (var l = 0; l < lines.length; l++) {
  37157. var points = lines[l];
  37158. for (var index = 0; index < points.length; index++) {
  37159. positions.push(points[index].x, points[index].y, points[index].z);
  37160. if (index > 0) {
  37161. indices.push(idx - 1);
  37162. indices.push(idx);
  37163. }
  37164. idx++;
  37165. }
  37166. }
  37167. var vertexData = new VertexData();
  37168. vertexData.indices = indices;
  37169. vertexData.positions = positions;
  37170. return vertexData;
  37171. };
  37172. /**
  37173. * Create the VertexData of the DashedLines.
  37174. */
  37175. VertexData.CreateDashedLines = function (options) {
  37176. var dashSize = options.dashSize || 3;
  37177. var gapSize = options.gapSize || 1;
  37178. var dashNb = options.dashNb || 200;
  37179. var points = options.points;
  37180. var positions = new Array();
  37181. var indices = new Array();
  37182. var curvect = BABYLON.Vector3.Zero();
  37183. var lg = 0;
  37184. var nb = 0;
  37185. var shft = 0;
  37186. var dashshft = 0;
  37187. var curshft = 0;
  37188. var idx = 0;
  37189. var i = 0;
  37190. for (i = 0; i < points.length - 1; i++) {
  37191. points[i + 1].subtractToRef(points[i], curvect);
  37192. lg += curvect.length();
  37193. }
  37194. shft = lg / dashNb;
  37195. dashshft = dashSize * shft / (dashSize + gapSize);
  37196. for (i = 0; i < points.length - 1; i++) {
  37197. points[i + 1].subtractToRef(points[i], curvect);
  37198. nb = Math.floor(curvect.length() / shft);
  37199. curvect.normalize();
  37200. for (var j = 0; j < nb; j++) {
  37201. curshft = shft * j;
  37202. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37203. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37204. indices.push(idx, idx + 1);
  37205. idx += 2;
  37206. }
  37207. }
  37208. // Result
  37209. var vertexData = new VertexData();
  37210. vertexData.positions = positions;
  37211. vertexData.indices = indices;
  37212. return vertexData;
  37213. };
  37214. /**
  37215. * Creates the VertexData of the Ground.
  37216. */
  37217. VertexData.CreateGround = function (options) {
  37218. var indices = [];
  37219. var positions = [];
  37220. var normals = [];
  37221. var uvs = [];
  37222. var row, col;
  37223. var width = options.width || 1;
  37224. var height = options.height || 1;
  37225. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37226. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37227. for (row = 0; row <= subdivisionsY; row++) {
  37228. for (col = 0; col <= subdivisionsX; col++) {
  37229. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37230. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37231. positions.push(position.x, position.y, position.z);
  37232. normals.push(normal.x, normal.y, normal.z);
  37233. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37234. }
  37235. }
  37236. for (row = 0; row < subdivisionsY; row++) {
  37237. for (col = 0; col < subdivisionsX; col++) {
  37238. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37239. indices.push(col + 1 + row * (subdivisionsX + 1));
  37240. indices.push(col + row * (subdivisionsX + 1));
  37241. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37242. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37243. indices.push(col + row * (subdivisionsX + 1));
  37244. }
  37245. }
  37246. // Result
  37247. var vertexData = new VertexData();
  37248. vertexData.indices = indices;
  37249. vertexData.positions = positions;
  37250. vertexData.normals = normals;
  37251. vertexData.uvs = uvs;
  37252. return vertexData;
  37253. };
  37254. /**
  37255. * Creates the VertexData of the TiledGround.
  37256. */
  37257. VertexData.CreateTiledGround = function (options) {
  37258. var xmin = options.xmin || -1.0;
  37259. var zmin = options.zmin || -1.0;
  37260. var xmax = options.xmax || 1.0;
  37261. var zmax = options.zmax || 1.0;
  37262. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37263. var precision = options.precision || { w: 1, h: 1 };
  37264. var indices = [];
  37265. var positions = [];
  37266. var normals = [];
  37267. var uvs = [];
  37268. var row, col, tileRow, tileCol;
  37269. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37270. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37271. precision.w = (precision.w < 1) ? 1 : precision.w;
  37272. precision.h = (precision.h < 1) ? 1 : precision.h;
  37273. var tileSize = {
  37274. 'w': (xmax - xmin) / subdivisions.w,
  37275. 'h': (zmax - zmin) / subdivisions.h
  37276. };
  37277. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37278. // Indices
  37279. var base = positions.length / 3;
  37280. var rowLength = precision.w + 1;
  37281. for (row = 0; row < precision.h; row++) {
  37282. for (col = 0; col < precision.w; col++) {
  37283. var square = [
  37284. base + col + row * rowLength,
  37285. base + (col + 1) + row * rowLength,
  37286. base + (col + 1) + (row + 1) * rowLength,
  37287. base + col + (row + 1) * rowLength
  37288. ];
  37289. indices.push(square[1]);
  37290. indices.push(square[2]);
  37291. indices.push(square[3]);
  37292. indices.push(square[0]);
  37293. indices.push(square[1]);
  37294. indices.push(square[3]);
  37295. }
  37296. }
  37297. // Position, normals and uvs
  37298. var position = BABYLON.Vector3.Zero();
  37299. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37300. for (row = 0; row <= precision.h; row++) {
  37301. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37302. for (col = 0; col <= precision.w; col++) {
  37303. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37304. position.y = 0;
  37305. positions.push(position.x, position.y, position.z);
  37306. normals.push(normal.x, normal.y, normal.z);
  37307. uvs.push(col / precision.w, row / precision.h);
  37308. }
  37309. }
  37310. }
  37311. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37312. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37313. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37314. }
  37315. }
  37316. // Result
  37317. var vertexData = new VertexData();
  37318. vertexData.indices = indices;
  37319. vertexData.positions = positions;
  37320. vertexData.normals = normals;
  37321. vertexData.uvs = uvs;
  37322. return vertexData;
  37323. };
  37324. /**
  37325. * Creates the VertexData of the Ground designed from a heightmap.
  37326. */
  37327. VertexData.CreateGroundFromHeightMap = function (options) {
  37328. var indices = [];
  37329. var positions = [];
  37330. var normals = [];
  37331. var uvs = [];
  37332. var row, col;
  37333. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37334. // Vertices
  37335. for (row = 0; row <= options.subdivisions; row++) {
  37336. for (col = 0; col <= options.subdivisions; col++) {
  37337. 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));
  37338. // Compute height
  37339. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37340. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37341. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37342. var r = options.buffer[pos] / 255.0;
  37343. var g = options.buffer[pos + 1] / 255.0;
  37344. var b = options.buffer[pos + 2] / 255.0;
  37345. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37346. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37347. // Add vertex
  37348. positions.push(position.x, position.y, position.z);
  37349. normals.push(0, 0, 0);
  37350. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37351. }
  37352. }
  37353. // Indices
  37354. for (row = 0; row < options.subdivisions; row++) {
  37355. for (col = 0; col < options.subdivisions; col++) {
  37356. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37357. indices.push(col + 1 + row * (options.subdivisions + 1));
  37358. indices.push(col + row * (options.subdivisions + 1));
  37359. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37360. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37361. indices.push(col + row * (options.subdivisions + 1));
  37362. }
  37363. }
  37364. // Normals
  37365. VertexData.ComputeNormals(positions, indices, normals);
  37366. // Result
  37367. var vertexData = new VertexData();
  37368. vertexData.indices = indices;
  37369. vertexData.positions = positions;
  37370. vertexData.normals = normals;
  37371. vertexData.uvs = uvs;
  37372. return vertexData;
  37373. };
  37374. /**
  37375. * Creates the VertexData of the Plane.
  37376. */
  37377. VertexData.CreatePlane = function (options) {
  37378. var indices = [];
  37379. var positions = [];
  37380. var normals = [];
  37381. var uvs = [];
  37382. var width = options.width || options.size || 1;
  37383. var height = options.height || options.size || 1;
  37384. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37385. // Vertices
  37386. var halfWidth = width / 2.0;
  37387. var halfHeight = height / 2.0;
  37388. positions.push(-halfWidth, -halfHeight, 0);
  37389. normals.push(0, 0, -1.0);
  37390. uvs.push(0.0, 0.0);
  37391. positions.push(halfWidth, -halfHeight, 0);
  37392. normals.push(0, 0, -1.0);
  37393. uvs.push(1.0, 0.0);
  37394. positions.push(halfWidth, halfHeight, 0);
  37395. normals.push(0, 0, -1.0);
  37396. uvs.push(1.0, 1.0);
  37397. positions.push(-halfWidth, halfHeight, 0);
  37398. normals.push(0, 0, -1.0);
  37399. uvs.push(0.0, 1.0);
  37400. // Indices
  37401. indices.push(0);
  37402. indices.push(1);
  37403. indices.push(2);
  37404. indices.push(0);
  37405. indices.push(2);
  37406. indices.push(3);
  37407. // Sides
  37408. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37409. // Result
  37410. var vertexData = new VertexData();
  37411. vertexData.indices = indices;
  37412. vertexData.positions = positions;
  37413. vertexData.normals = normals;
  37414. vertexData.uvs = uvs;
  37415. return vertexData;
  37416. };
  37417. /**
  37418. * Creates the VertexData of the Disc or regular Polygon.
  37419. */
  37420. VertexData.CreateDisc = function (options) {
  37421. var positions = [];
  37422. var indices = [];
  37423. var normals = [];
  37424. var uvs = [];
  37425. var radius = options.radius || 0.5;
  37426. var tessellation = options.tessellation || 64;
  37427. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37429. // positions and uvs
  37430. positions.push(0, 0, 0); // disc center first
  37431. uvs.push(0.5, 0.5);
  37432. var theta = Math.PI * 2 * arc;
  37433. var step = theta / tessellation;
  37434. for (var a = 0; a < theta; a += step) {
  37435. var x = Math.cos(a);
  37436. var y = Math.sin(a);
  37437. var u = (x + 1) / 2;
  37438. var v = (1 - y) / 2;
  37439. positions.push(radius * x, radius * y, 0);
  37440. uvs.push(u, v);
  37441. }
  37442. if (arc === 1) {
  37443. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37444. uvs.push(uvs[2], uvs[3]);
  37445. }
  37446. //indices
  37447. var vertexNb = positions.length / 3;
  37448. for (var i = 1; i < vertexNb - 1; i++) {
  37449. indices.push(i + 1, 0, i);
  37450. }
  37451. // result
  37452. VertexData.ComputeNormals(positions, indices, normals);
  37453. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37454. var vertexData = new VertexData();
  37455. vertexData.indices = indices;
  37456. vertexData.positions = positions;
  37457. vertexData.normals = normals;
  37458. vertexData.uvs = uvs;
  37459. return vertexData;
  37460. };
  37461. /**
  37462. * Creates the VertexData of the IcoSphere.
  37463. */
  37464. VertexData.CreateIcoSphere = function (options) {
  37465. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37466. var radius = options.radius || 1;
  37467. var flat = (options.flat === undefined) ? true : options.flat;
  37468. var subdivisions = options.subdivisions || 4;
  37469. var radiusX = options.radiusX || radius;
  37470. var radiusY = options.radiusY || radius;
  37471. var radiusZ = options.radiusZ || radius;
  37472. var t = (1 + Math.sqrt(5)) / 2;
  37473. // 12 vertex x,y,z
  37474. var ico_vertices = [
  37475. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37476. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37477. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37478. ];
  37479. // index of 3 vertex makes a face of icopshere
  37480. var ico_indices = [
  37481. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37482. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37483. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37484. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37485. ];
  37486. // vertex for uv have aliased position, not for UV
  37487. var vertices_unalias_id = [
  37488. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37489. // vertex alias
  37490. 0,
  37491. 2,
  37492. 3,
  37493. 3,
  37494. 3,
  37495. 4,
  37496. 7,
  37497. 8,
  37498. 9,
  37499. 9,
  37500. 10,
  37501. 11 // 23: B + 12
  37502. ];
  37503. // uv as integer step (not pixels !)
  37504. var ico_vertexuv = [
  37505. 5, 1, 3, 1, 6, 4, 0, 0,
  37506. 5, 3, 4, 2, 2, 2, 4, 0,
  37507. 2, 0, 1, 1, 6, 0, 6, 2,
  37508. // vertex alias (for same vertex on different faces)
  37509. 0, 4,
  37510. 3, 3,
  37511. 4, 4,
  37512. 3, 1,
  37513. 4, 2,
  37514. 4, 4,
  37515. 0, 2,
  37516. 1, 1,
  37517. 2, 2,
  37518. 3, 3,
  37519. 1, 3,
  37520. 2, 4 // 23: B + 12
  37521. ];
  37522. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37523. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37524. // First island of uv mapping
  37525. // v = 4h 3+ 2
  37526. // v = 3h 9+ 4
  37527. // v = 2h 9+ 5 B
  37528. // v = 1h 9 1 0
  37529. // v = 0h 3 8 7 A
  37530. // u = 0 1 2 3 4 5 6 *a
  37531. // Second island of uv mapping
  37532. // v = 4h 0+ B+ 4+
  37533. // v = 3h A+ 2+
  37534. // v = 2h 7+ 6 3+
  37535. // v = 1h 8+ 3+
  37536. // v = 0h
  37537. // u = 0 1 2 3 4 5 6 *a
  37538. // Face layout on texture UV mapping
  37539. // ============
  37540. // \ 4 /\ 16 / ======
  37541. // \ / \ / /\ 11 /
  37542. // \/ 7 \/ / \ /
  37543. // ======= / 10 \/
  37544. // /\ 17 /\ =======
  37545. // / \ / \ \ 15 /\
  37546. // / 8 \/ 12 \ \ / \
  37547. // ============ \/ 6 \
  37548. // \ 18 /\ ============
  37549. // \ / \ \ 5 /\ 0 /
  37550. // \/ 13 \ \ / \ /
  37551. // ======= \/ 1 \/
  37552. // =============
  37553. // /\ 19 /\ 2 /\
  37554. // / \ / \ / \
  37555. // / 14 \/ 9 \/ 3 \
  37556. // ===================
  37557. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37558. var ustep = 138 / 1024;
  37559. var vstep = 239 / 1024;
  37560. var uoffset = 60 / 1024;
  37561. var voffset = 26 / 1024;
  37562. // Second island should have margin, not to touch the first island
  37563. // avoid any borderline artefact in pixel rounding
  37564. var island_u_offset = -40 / 1024;
  37565. var island_v_offset = +20 / 1024;
  37566. // face is either island 0 or 1 :
  37567. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37568. var island = [
  37569. 0, 0, 0, 0, 1,
  37570. 0, 0, 1, 1, 0,
  37571. 0, 0, 1, 1, 0,
  37572. 0, 1, 1, 1, 0 // 15 - 19
  37573. ];
  37574. var indices = [];
  37575. var positions = [];
  37576. var normals = [];
  37577. var uvs = [];
  37578. var current_indice = 0;
  37579. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37580. var face_vertex_pos = new Array(3);
  37581. var face_vertex_uv = new Array(3);
  37582. var v012;
  37583. for (v012 = 0; v012 < 3; v012++) {
  37584. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37585. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37586. }
  37587. // create all with normals
  37588. for (var face = 0; face < 20; face++) {
  37589. // 3 vertex per face
  37590. for (v012 = 0; v012 < 3; v012++) {
  37591. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37592. var v_id = ico_indices[3 * face + v012];
  37593. // vertex have 3D position (x,y,z)
  37594. 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]);
  37595. // Normalize to get normal, then scale to radius
  37596. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37597. // uv Coordinates from vertex ID
  37598. 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);
  37599. }
  37600. // Subdivide the face (interpolate pos, norm, uv)
  37601. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37602. // - norm is linear interpolation of vertex corner normal
  37603. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37604. // - uv is linear interpolation
  37605. //
  37606. // Topology is as below for sub-divide by 2
  37607. // vertex shown as v0,v1,v2
  37608. // interp index is i1 to progress in range [v0,v1[
  37609. // interp index is i2 to progress in range [v0,v2[
  37610. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37611. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37612. //
  37613. //
  37614. // i2 v2
  37615. // ^ ^
  37616. // / / \
  37617. // / / \
  37618. // / / \
  37619. // / / (0,1) \
  37620. // / #---------\
  37621. // / / \ (0,0)'/ \
  37622. // / / \ / \
  37623. // / / \ / \
  37624. // / / (0,0) \ / (1,0) \
  37625. // / #---------#---------\
  37626. // v0 v1
  37627. //
  37628. // --------------------> i1
  37629. //
  37630. // interp of (i1,i2):
  37631. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37632. // along i1 : lerp(x0,x1, i1/(S-i2))
  37633. //
  37634. // centroid of triangle is needed to get help normal computation
  37635. // (c1,c2) are used for centroid location
  37636. var interp_vertex = function (i1, i2, c1, c2) {
  37637. // vertex is interpolated from
  37638. // - face_vertex_pos[0..2]
  37639. // - face_vertex_uv[0..2]
  37640. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37641. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37642. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37643. pos_interp.normalize();
  37644. var vertex_normal;
  37645. if (flat) {
  37646. // in flat mode, recalculate normal as face centroid normal
  37647. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37648. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37649. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37650. }
  37651. else {
  37652. // in smooth mode, recalculate normal from each single vertex position
  37653. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37654. }
  37655. // Vertex normal need correction due to X,Y,Z radius scaling
  37656. vertex_normal.x /= radiusX;
  37657. vertex_normal.y /= radiusY;
  37658. vertex_normal.z /= radiusZ;
  37659. vertex_normal.normalize();
  37660. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37661. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37662. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37663. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37664. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37665. uvs.push(uv_interp.x, uv_interp.y);
  37666. // push each vertex has member of a face
  37667. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37668. indices.push(current_indice);
  37669. current_indice++;
  37670. };
  37671. for (var i2 = 0; i2 < subdivisions; i2++) {
  37672. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37673. // face : (i1,i2) for /\ :
  37674. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37675. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37676. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37677. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37678. if (i1 + i2 + 1 < subdivisions) {
  37679. // face : (i1,i2)' for \/ :
  37680. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37681. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37682. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37683. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37684. }
  37685. }
  37686. }
  37687. }
  37688. // Sides
  37689. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37690. // Result
  37691. var vertexData = new VertexData();
  37692. vertexData.indices = indices;
  37693. vertexData.positions = positions;
  37694. vertexData.normals = normals;
  37695. vertexData.uvs = uvs;
  37696. return vertexData;
  37697. };
  37698. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37699. /**
  37700. * Creates the VertexData of the Polyhedron.
  37701. */
  37702. VertexData.CreatePolyhedron = function (options) {
  37703. // provided polyhedron types :
  37704. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37705. // 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)
  37706. var polyhedra = [];
  37707. 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]] };
  37708. 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]] };
  37709. polyhedra[2] = {
  37710. 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]],
  37711. 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]]
  37712. };
  37713. polyhedra[3] = {
  37714. 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]],
  37715. 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]]
  37716. };
  37717. polyhedra[4] = {
  37718. 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]],
  37719. 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]]
  37720. };
  37721. 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]] };
  37722. 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]] };
  37723. 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]] };
  37724. 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]] };
  37725. 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]] };
  37726. 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]] };
  37727. 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]] };
  37728. 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]] };
  37729. 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]] };
  37730. polyhedra[14] = {
  37731. 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]],
  37732. 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]]
  37733. };
  37734. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37735. var size = options.size;
  37736. var sizeX = options.sizeX || size || 1;
  37737. var sizeY = options.sizeY || size || 1;
  37738. var sizeZ = options.sizeZ || size || 1;
  37739. var data = options.custom || polyhedra[type];
  37740. var nbfaces = data.face.length;
  37741. var faceUV = options.faceUV || new Array(nbfaces);
  37742. var faceColors = options.faceColors;
  37743. var flat = (options.flat === undefined) ? true : options.flat;
  37744. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37745. var positions = [];
  37746. var indices = [];
  37747. var normals = [];
  37748. var uvs = [];
  37749. var colors = [];
  37750. var index = 0;
  37751. var faceIdx = 0; // face cursor in the array "indexes"
  37752. var indexes = [];
  37753. var i = 0;
  37754. var f = 0;
  37755. var u, v, ang, x, y, tmp;
  37756. // default face colors and UV if undefined
  37757. if (flat) {
  37758. for (f = 0; f < nbfaces; f++) {
  37759. if (faceColors && faceColors[f] === undefined) {
  37760. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37761. }
  37762. if (faceUV && faceUV[f] === undefined) {
  37763. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37764. }
  37765. }
  37766. }
  37767. if (!flat) {
  37768. for (i = 0; i < data.vertex.length; i++) {
  37769. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37770. uvs.push(0, 0);
  37771. }
  37772. for (f = 0; f < nbfaces; f++) {
  37773. for (i = 0; i < data.face[f].length - 2; i++) {
  37774. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37775. }
  37776. }
  37777. }
  37778. else {
  37779. for (f = 0; f < nbfaces; f++) {
  37780. var fl = data.face[f].length; // number of vertices of the current face
  37781. ang = 2 * Math.PI / fl;
  37782. x = 0.5 * Math.tan(ang / 2);
  37783. y = 0.5;
  37784. // positions, uvs, colors
  37785. for (i = 0; i < fl; i++) {
  37786. // positions
  37787. 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);
  37788. indexes.push(index);
  37789. index++;
  37790. // uvs
  37791. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37792. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37793. uvs.push(u, v);
  37794. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37795. y = x * Math.sin(ang) + y * Math.cos(ang);
  37796. x = tmp;
  37797. // colors
  37798. if (faceColors) {
  37799. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37800. }
  37801. }
  37802. // indices from indexes
  37803. for (i = 0; i < fl - 2; i++) {
  37804. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37805. }
  37806. faceIdx += fl;
  37807. }
  37808. }
  37809. VertexData.ComputeNormals(positions, indices, normals);
  37810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37811. var vertexData = new VertexData();
  37812. vertexData.positions = positions;
  37813. vertexData.indices = indices;
  37814. vertexData.normals = normals;
  37815. vertexData.uvs = uvs;
  37816. if (faceColors && flat) {
  37817. vertexData.colors = colors;
  37818. }
  37819. return vertexData;
  37820. };
  37821. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37822. /**
  37823. * Creates the VertexData of the Torus Knot.
  37824. */
  37825. VertexData.CreateTorusKnot = function (options) {
  37826. var indices = [];
  37827. var positions = [];
  37828. var normals = [];
  37829. var uvs = [];
  37830. var radius = options.radius || 2;
  37831. var tube = options.tube || 0.5;
  37832. var radialSegments = options.radialSegments || 32;
  37833. var tubularSegments = options.tubularSegments || 32;
  37834. var p = options.p || 2;
  37835. var q = options.q || 3;
  37836. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37837. // Helper
  37838. var getPos = function (angle) {
  37839. var cu = Math.cos(angle);
  37840. var su = Math.sin(angle);
  37841. var quOverP = q / p * angle;
  37842. var cs = Math.cos(quOverP);
  37843. var tx = radius * (2 + cs) * 0.5 * cu;
  37844. var ty = radius * (2 + cs) * su * 0.5;
  37845. var tz = radius * Math.sin(quOverP) * 0.5;
  37846. return new BABYLON.Vector3(tx, ty, tz);
  37847. };
  37848. // Vertices
  37849. var i;
  37850. var j;
  37851. for (i = 0; i <= radialSegments; i++) {
  37852. var modI = i % radialSegments;
  37853. var u = modI / radialSegments * 2 * p * Math.PI;
  37854. var p1 = getPos(u);
  37855. var p2 = getPos(u + 0.01);
  37856. var tang = p2.subtract(p1);
  37857. var n = p2.add(p1);
  37858. var bitan = BABYLON.Vector3.Cross(tang, n);
  37859. n = BABYLON.Vector3.Cross(bitan, tang);
  37860. bitan.normalize();
  37861. n.normalize();
  37862. for (j = 0; j < tubularSegments; j++) {
  37863. var modJ = j % tubularSegments;
  37864. var v = modJ / tubularSegments * 2 * Math.PI;
  37865. var cx = -tube * Math.cos(v);
  37866. var cy = tube * Math.sin(v);
  37867. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37868. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37869. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37870. uvs.push(i / radialSegments);
  37871. uvs.push(j / tubularSegments);
  37872. }
  37873. }
  37874. for (i = 0; i < radialSegments; i++) {
  37875. for (j = 0; j < tubularSegments; j++) {
  37876. var jNext = (j + 1) % tubularSegments;
  37877. var a = i * tubularSegments + j;
  37878. var b = (i + 1) * tubularSegments + j;
  37879. var c = (i + 1) * tubularSegments + jNext;
  37880. var d = i * tubularSegments + jNext;
  37881. indices.push(d);
  37882. indices.push(b);
  37883. indices.push(a);
  37884. indices.push(d);
  37885. indices.push(c);
  37886. indices.push(b);
  37887. }
  37888. }
  37889. // Normals
  37890. VertexData.ComputeNormals(positions, indices, normals);
  37891. // Sides
  37892. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37893. // Result
  37894. var vertexData = new VertexData();
  37895. vertexData.indices = indices;
  37896. vertexData.positions = positions;
  37897. vertexData.normals = normals;
  37898. vertexData.uvs = uvs;
  37899. return vertexData;
  37900. };
  37901. // Tools
  37902. /**
  37903. * @param {any} - positions (number[] or Float32Array)
  37904. * @param {any} - indices (number[] or Uint16Array)
  37905. * @param {any} - normals (number[] or Float32Array)
  37906. * options (optional) :
  37907. * facetPositions : optional array of facet positions (vector3)
  37908. * facetNormals : optional array of facet normals (vector3)
  37909. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37910. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37911. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37912. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37913. * bInfo : optional bounding info, required for facetPartitioning computation
  37914. */
  37915. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37916. // temporary scalar variables
  37917. var index = 0; // facet index
  37918. var p1p2x = 0.0; // p1p2 vector x coordinate
  37919. var p1p2y = 0.0; // p1p2 vector y coordinate
  37920. var p1p2z = 0.0; // p1p2 vector z coordinate
  37921. var p3p2x = 0.0; // p3p2 vector x coordinate
  37922. var p3p2y = 0.0; // p3p2 vector y coordinate
  37923. var p3p2z = 0.0; // p3p2 vector z coordinate
  37924. var faceNormalx = 0.0; // facet normal x coordinate
  37925. var faceNormaly = 0.0; // facet normal y coordinate
  37926. var faceNormalz = 0.0; // facet normal z coordinate
  37927. var length = 0.0; // facet normal length before normalization
  37928. var v1x = 0; // vector1 x index in the positions array
  37929. var v1y = 0; // vector1 y index in the positions array
  37930. var v1z = 0; // vector1 z index in the positions array
  37931. var v2x = 0; // vector2 x index in the positions array
  37932. var v2y = 0; // vector2 y index in the positions array
  37933. var v2z = 0; // vector2 z index in the positions array
  37934. var v3x = 0; // vector3 x index in the positions array
  37935. var v3y = 0; // vector3 y index in the positions array
  37936. var v3z = 0; // vector3 z index in the positions array
  37937. var computeFacetNormals = false;
  37938. var computeFacetPositions = false;
  37939. var computeFacetPartitioning = false;
  37940. if (options) {
  37941. computeFacetNormals = (options.facetNormals) ? true : false;
  37942. computeFacetPositions = (options.facetPositions) ? true : false;
  37943. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37944. }
  37945. // facetPartitioning reinit if needed
  37946. if (computeFacetPartitioning) {
  37947. var ox = 0; // X partitioning index for facet position
  37948. var oy = 0; // Y partinioning index for facet position
  37949. var oz = 0; // Z partinioning index for facet position
  37950. var b1x = 0; // X partitioning index for facet v1 vertex
  37951. var b1y = 0; // Y partitioning index for facet v1 vertex
  37952. var b1z = 0; // z partitioning index for facet v1 vertex
  37953. var b2x = 0; // X partitioning index for facet v2 vertex
  37954. var b2y = 0; // Y partitioning index for facet v2 vertex
  37955. var b2z = 0; // Z partitioning index for facet v2 vertex
  37956. var b3x = 0; // X partitioning index for facet v3 vertex
  37957. var b3y = 0; // Y partitioning index for facet v3 vertex
  37958. var b3z = 0; // Z partitioning index for facet v3 vertex
  37959. var block_idx_o = 0; // facet barycenter block index
  37960. var block_idx_v1 = 0; // v1 vertex block index
  37961. var block_idx_v2 = 0; // v2 vertex block index
  37962. var block_idx_v3 = 0; // v3 vertex block index
  37963. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37964. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37965. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  37966. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  37967. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  37968. var subSq = options.subDiv.max * options.subDiv.max;
  37969. options.facetPartitioning.length = 0;
  37970. }
  37971. // reset the normals
  37972. for (index = 0; index < positions.length; index++) {
  37973. normals[index] = 0.0;
  37974. }
  37975. // Loop : 1 indice triplet = 1 facet
  37976. var nbFaces = indices.length / 3;
  37977. for (index = 0; index < nbFaces; index++) {
  37978. // get the indexes of the coordinates of each vertex of the facet
  37979. v1x = indices[index * 3] * 3;
  37980. v1y = v1x + 1;
  37981. v1z = v1x + 2;
  37982. v2x = indices[index * 3 + 1] * 3;
  37983. v2y = v2x + 1;
  37984. v2z = v2x + 2;
  37985. v3x = indices[index * 3 + 2] * 3;
  37986. v3y = v3x + 1;
  37987. v3z = v3x + 2;
  37988. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37989. p1p2y = positions[v1y] - positions[v2y];
  37990. p1p2z = positions[v1z] - positions[v2z];
  37991. p3p2x = positions[v3x] - positions[v2x];
  37992. p3p2y = positions[v3y] - positions[v2y];
  37993. p3p2z = positions[v3z] - positions[v2z];
  37994. // compute the face normal with the cross product
  37995. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  37996. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  37997. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  37998. // normalize this normal and store it in the array facetData
  37999. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38000. length = (length === 0) ? 1.0 : length;
  38001. faceNormalx /= length;
  38002. faceNormaly /= length;
  38003. faceNormalz /= length;
  38004. if (computeFacetNormals) {
  38005. options.facetNormals[index].x = faceNormalx;
  38006. options.facetNormals[index].y = faceNormaly;
  38007. options.facetNormals[index].z = faceNormalz;
  38008. }
  38009. if (computeFacetPositions) {
  38010. // compute and the facet barycenter coordinates in the array facetPositions
  38011. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38012. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38013. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38014. }
  38015. if (computeFacetPartitioning) {
  38016. // store the facet indexes in arrays in the main facetPartitioning array :
  38017. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38018. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38019. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38020. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38021. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38022. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38023. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38024. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38025. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38026. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38027. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38028. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38029. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38030. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38031. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38032. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38033. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38034. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38035. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38036. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38037. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38038. // push each facet index in each block containing the vertex
  38039. options.facetPartitioning[block_idx_v1].push(index);
  38040. if (block_idx_v2 != block_idx_v1) {
  38041. options.facetPartitioning[block_idx_v2].push(index);
  38042. }
  38043. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38044. options.facetPartitioning[block_idx_v3].push(index);
  38045. }
  38046. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38047. options.facetPartitioning[block_idx_o].push(index);
  38048. }
  38049. }
  38050. // compute the normals anyway
  38051. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38052. normals[v1y] += faceNormaly;
  38053. normals[v1z] += faceNormalz;
  38054. normals[v2x] += faceNormalx;
  38055. normals[v2y] += faceNormaly;
  38056. normals[v2z] += faceNormalz;
  38057. normals[v3x] += faceNormalx;
  38058. normals[v3y] += faceNormaly;
  38059. normals[v3z] += faceNormalz;
  38060. }
  38061. // last normalization of each normal
  38062. for (index = 0; index < normals.length / 3; index++) {
  38063. faceNormalx = normals[index * 3];
  38064. faceNormaly = normals[index * 3 + 1];
  38065. faceNormalz = normals[index * 3 + 2];
  38066. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38067. length = (length === 0) ? 1.0 : length;
  38068. faceNormalx /= length;
  38069. faceNormaly /= length;
  38070. faceNormalz /= length;
  38071. normals[index * 3] = faceNormalx;
  38072. normals[index * 3 + 1] = faceNormaly;
  38073. normals[index * 3 + 2] = faceNormalz;
  38074. }
  38075. };
  38076. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  38077. var li = indices.length;
  38078. var ln = normals.length;
  38079. var i;
  38080. var n;
  38081. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38082. switch (sideOrientation) {
  38083. case BABYLON.Mesh.FRONTSIDE:
  38084. // nothing changed
  38085. break;
  38086. case BABYLON.Mesh.BACKSIDE:
  38087. var tmp;
  38088. // indices
  38089. for (i = 0; i < li; i += 3) {
  38090. tmp = indices[i];
  38091. indices[i] = indices[i + 2];
  38092. indices[i + 2] = tmp;
  38093. }
  38094. // normals
  38095. for (n = 0; n < ln; n++) {
  38096. normals[n] = -normals[n];
  38097. }
  38098. break;
  38099. case BABYLON.Mesh.DOUBLESIDE:
  38100. // positions
  38101. var lp = positions.length;
  38102. var l = lp / 3;
  38103. for (var p = 0; p < lp; p++) {
  38104. positions[lp + p] = positions[p];
  38105. }
  38106. // indices
  38107. for (i = 0; i < li; i += 3) {
  38108. indices[i + li] = indices[i + 2] + l;
  38109. indices[i + 1 + li] = indices[i + 1] + l;
  38110. indices[i + 2 + li] = indices[i] + l;
  38111. }
  38112. // normals
  38113. for (n = 0; n < ln; n++) {
  38114. normals[ln + n] = -normals[n];
  38115. }
  38116. // uvs
  38117. var lu = uvs.length;
  38118. for (var u = 0; u < lu; u++) {
  38119. uvs[u + lu] = uvs[u];
  38120. }
  38121. break;
  38122. }
  38123. };
  38124. /**
  38125. * Creates a new VertexData from the imported parameters.
  38126. */
  38127. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38128. var vertexData = new VertexData();
  38129. // positions
  38130. var positions = parsedVertexData.positions;
  38131. if (positions) {
  38132. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38133. }
  38134. // normals
  38135. var normals = parsedVertexData.normals;
  38136. if (normals) {
  38137. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38138. }
  38139. // uvs
  38140. var uvs = parsedVertexData.uvs;
  38141. if (uvs) {
  38142. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38143. }
  38144. // uv2s
  38145. var uv2s = parsedVertexData.uv2s;
  38146. if (uv2s) {
  38147. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38148. }
  38149. // uv3s
  38150. var uv3s = parsedVertexData.uv3s;
  38151. if (uv3s) {
  38152. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38153. }
  38154. // uv4s
  38155. var uv4s = parsedVertexData.uv4s;
  38156. if (uv4s) {
  38157. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38158. }
  38159. // uv5s
  38160. var uv5s = parsedVertexData.uv5s;
  38161. if (uv5s) {
  38162. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38163. }
  38164. // uv6s
  38165. var uv6s = parsedVertexData.uv6s;
  38166. if (uv6s) {
  38167. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38168. }
  38169. // colors
  38170. var colors = parsedVertexData.colors;
  38171. if (colors) {
  38172. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38173. }
  38174. // matricesIndices
  38175. var matricesIndices = parsedVertexData.matricesIndices;
  38176. if (matricesIndices) {
  38177. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38178. }
  38179. // matricesWeights
  38180. var matricesWeights = parsedVertexData.matricesWeights;
  38181. if (matricesWeights) {
  38182. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38183. }
  38184. // indices
  38185. var indices = parsedVertexData.indices;
  38186. if (indices) {
  38187. vertexData.indices = indices;
  38188. }
  38189. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38190. };
  38191. return VertexData;
  38192. }());
  38193. BABYLON.VertexData = VertexData;
  38194. })(BABYLON || (BABYLON = {}));
  38195. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38196. var BABYLON;
  38197. (function (BABYLON) {
  38198. var Tags = (function () {
  38199. function Tags() {
  38200. }
  38201. Tags.EnableFor = function (obj) {
  38202. obj._tags = obj._tags || {};
  38203. obj.hasTags = function () {
  38204. return Tags.HasTags(obj);
  38205. };
  38206. obj.addTags = function (tagsString) {
  38207. return Tags.AddTagsTo(obj, tagsString);
  38208. };
  38209. obj.removeTags = function (tagsString) {
  38210. return Tags.RemoveTagsFrom(obj, tagsString);
  38211. };
  38212. obj.matchesTagsQuery = function (tagsQuery) {
  38213. return Tags.MatchesQuery(obj, tagsQuery);
  38214. };
  38215. };
  38216. Tags.DisableFor = function (obj) {
  38217. delete obj._tags;
  38218. delete obj.hasTags;
  38219. delete obj.addTags;
  38220. delete obj.removeTags;
  38221. delete obj.matchesTagsQuery;
  38222. };
  38223. Tags.HasTags = function (obj) {
  38224. if (!obj._tags) {
  38225. return false;
  38226. }
  38227. return !BABYLON.Tools.IsEmpty(obj._tags);
  38228. };
  38229. Tags.GetTags = function (obj, asString) {
  38230. if (asString === void 0) { asString = true; }
  38231. if (!obj._tags) {
  38232. return null;
  38233. }
  38234. if (asString) {
  38235. var tagsArray = [];
  38236. for (var tag in obj._tags) {
  38237. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  38238. tagsArray.push(tag);
  38239. }
  38240. }
  38241. return tagsArray.join(" ");
  38242. }
  38243. else {
  38244. return obj._tags;
  38245. }
  38246. };
  38247. // the tags 'true' and 'false' are reserved and cannot be used as tags
  38248. // a tag cannot start with '||', '&&', and '!'
  38249. // it cannot contain whitespaces
  38250. Tags.AddTagsTo = function (obj, tagsString) {
  38251. if (!tagsString) {
  38252. return;
  38253. }
  38254. if (typeof tagsString !== "string") {
  38255. return;
  38256. }
  38257. var tags = tagsString.split(" ");
  38258. tags.forEach(function (tag, index, array) {
  38259. Tags._AddTagTo(obj, tag);
  38260. });
  38261. };
  38262. Tags._AddTagTo = function (obj, tag) {
  38263. tag = tag.trim();
  38264. if (tag === "" || tag === "true" || tag === "false") {
  38265. return;
  38266. }
  38267. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  38268. return;
  38269. }
  38270. Tags.EnableFor(obj);
  38271. obj._tags[tag] = true;
  38272. };
  38273. Tags.RemoveTagsFrom = function (obj, tagsString) {
  38274. if (!Tags.HasTags(obj)) {
  38275. return;
  38276. }
  38277. var tags = tagsString.split(" ");
  38278. for (var t in tags) {
  38279. Tags._RemoveTagFrom(obj, tags[t]);
  38280. }
  38281. };
  38282. Tags._RemoveTagFrom = function (obj, tag) {
  38283. delete obj._tags[tag];
  38284. };
  38285. Tags.MatchesQuery = function (obj, tagsQuery) {
  38286. if (tagsQuery === undefined) {
  38287. return true;
  38288. }
  38289. if (tagsQuery === "") {
  38290. return Tags.HasTags(obj);
  38291. }
  38292. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  38293. };
  38294. return Tags;
  38295. }());
  38296. BABYLON.Tags = Tags;
  38297. })(BABYLON || (BABYLON = {}));
  38298. //# sourceMappingURL=babylon.tags.js.map
  38299. var BABYLON;
  38300. (function (BABYLON) {
  38301. var Internals;
  38302. (function (Internals) {
  38303. var AndOrNotEvaluator = (function () {
  38304. function AndOrNotEvaluator() {
  38305. }
  38306. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  38307. if (!query.match(/\([^\(\)]*\)/g)) {
  38308. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  38309. }
  38310. else {
  38311. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  38312. // remove parenthesis
  38313. r = r.slice(1, r.length - 1);
  38314. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  38315. });
  38316. }
  38317. if (query === "true") {
  38318. return true;
  38319. }
  38320. if (query === "false") {
  38321. return false;
  38322. }
  38323. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  38324. };
  38325. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  38326. evaluateCallback = evaluateCallback || (function (r) {
  38327. return r === "true" ? true : false;
  38328. });
  38329. var result;
  38330. var or = parenthesisContent.split("||");
  38331. for (var i in or) {
  38332. if (or.hasOwnProperty(i)) {
  38333. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  38334. var and = ori.split("&&");
  38335. if (and.length > 1) {
  38336. for (var j = 0; j < and.length; ++j) {
  38337. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  38338. if (andj !== "true" && andj !== "false") {
  38339. if (andj[0] === "!") {
  38340. result = !evaluateCallback(andj.substring(1));
  38341. }
  38342. else {
  38343. result = evaluateCallback(andj);
  38344. }
  38345. }
  38346. else {
  38347. result = andj === "true" ? true : false;
  38348. }
  38349. if (!result) {
  38350. ori = "false";
  38351. break;
  38352. }
  38353. }
  38354. }
  38355. if (result || ori === "true") {
  38356. result = true;
  38357. break;
  38358. }
  38359. // result equals false (or undefined)
  38360. if (ori !== "true" && ori !== "false") {
  38361. if (ori[0] === "!") {
  38362. result = !evaluateCallback(ori.substring(1));
  38363. }
  38364. else {
  38365. result = evaluateCallback(ori);
  38366. }
  38367. }
  38368. else {
  38369. result = ori === "true" ? true : false;
  38370. }
  38371. }
  38372. }
  38373. // the whole parenthesis scope is replaced by 'true' or 'false'
  38374. return result ? "true" : "false";
  38375. };
  38376. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  38377. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  38378. // remove whitespaces
  38379. r = r.replace(/[\s]/g, function () { return ""; });
  38380. return r.length % 2 ? "!" : "";
  38381. });
  38382. booleanString = booleanString.trim();
  38383. if (booleanString === "!true") {
  38384. booleanString = "false";
  38385. }
  38386. else if (booleanString === "!false") {
  38387. booleanString = "true";
  38388. }
  38389. return booleanString;
  38390. };
  38391. return AndOrNotEvaluator;
  38392. }());
  38393. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  38394. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38395. })(BABYLON || (BABYLON = {}));
  38396. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  38397. var BABYLON;
  38398. (function (BABYLON) {
  38399. var PostProcessRenderPass = (function () {
  38400. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  38401. this._enabled = true;
  38402. this._refCount = 0;
  38403. this._name = name;
  38404. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  38405. this.setRenderList(renderList);
  38406. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  38407. this._renderTexture.onAfterRenderObservable.add(afterRender);
  38408. this._scene = scene;
  38409. this._renderList = renderList;
  38410. }
  38411. // private
  38412. PostProcessRenderPass.prototype._incRefCount = function () {
  38413. if (this._refCount === 0) {
  38414. this._scene.customRenderTargets.push(this._renderTexture);
  38415. }
  38416. return ++this._refCount;
  38417. };
  38418. PostProcessRenderPass.prototype._decRefCount = function () {
  38419. this._refCount--;
  38420. if (this._refCount <= 0) {
  38421. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  38422. }
  38423. return this._refCount;
  38424. };
  38425. PostProcessRenderPass.prototype._update = function () {
  38426. this.setRenderList(this._renderList);
  38427. };
  38428. // public
  38429. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  38430. this._renderTexture.renderList = renderList;
  38431. };
  38432. PostProcessRenderPass.prototype.getRenderTexture = function () {
  38433. return this._renderTexture;
  38434. };
  38435. return PostProcessRenderPass;
  38436. }());
  38437. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  38438. })(BABYLON || (BABYLON = {}));
  38439. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  38440. var BABYLON;
  38441. (function (BABYLON) {
  38442. var PostProcessRenderEffect = (function () {
  38443. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  38444. this._engine = engine;
  38445. this._name = name;
  38446. this._singleInstance = singleInstance || true;
  38447. this._getPostProcess = getPostProcess;
  38448. this._cameras = [];
  38449. this._indicesForCamera = [];
  38450. this._postProcesses = {};
  38451. this._renderPasses = {};
  38452. this._renderEffectAsPasses = {};
  38453. }
  38454. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  38455. get: function () {
  38456. for (var index in this._postProcesses) {
  38457. if (!this._postProcesses[index].isSupported) {
  38458. return false;
  38459. }
  38460. }
  38461. return true;
  38462. },
  38463. enumerable: true,
  38464. configurable: true
  38465. });
  38466. PostProcessRenderEffect.prototype._update = function () {
  38467. for (var renderPassName in this._renderPasses) {
  38468. this._renderPasses[renderPassName]._update();
  38469. }
  38470. };
  38471. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  38472. this._renderPasses[renderPass._name] = renderPass;
  38473. this._linkParameters();
  38474. };
  38475. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  38476. delete this._renderPasses[renderPass._name];
  38477. this._linkParameters();
  38478. };
  38479. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  38480. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  38481. this._linkParameters();
  38482. };
  38483. PostProcessRenderEffect.prototype.getPass = function (passName) {
  38484. for (var renderPassName in this._renderPasses) {
  38485. if (renderPassName === passName) {
  38486. return this._renderPasses[passName];
  38487. }
  38488. }
  38489. };
  38490. PostProcessRenderEffect.prototype.emptyPasses = function () {
  38491. this._renderPasses = {};
  38492. this._linkParameters();
  38493. };
  38494. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  38495. var cameraKey;
  38496. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38497. for (var i = 0; i < _cam.length; i++) {
  38498. var camera = _cam[i];
  38499. var cameraName = camera.name;
  38500. if (this._singleInstance) {
  38501. cameraKey = 0;
  38502. }
  38503. else {
  38504. cameraKey = cameraName;
  38505. }
  38506. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  38507. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  38508. if (!this._indicesForCamera[cameraName]) {
  38509. this._indicesForCamera[cameraName] = [];
  38510. }
  38511. this._indicesForCamera[cameraName].push(index);
  38512. if (this._cameras.indexOf(camera) === -1) {
  38513. this._cameras[cameraName] = camera;
  38514. }
  38515. for (var passName in this._renderPasses) {
  38516. this._renderPasses[passName]._incRefCount();
  38517. }
  38518. }
  38519. this._linkParameters();
  38520. };
  38521. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  38522. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38523. for (var i = 0; i < _cam.length; i++) {
  38524. var camera = _cam[i];
  38525. var cameraName = camera.name;
  38526. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  38527. var index = this._cameras.indexOf(cameraName);
  38528. this._indicesForCamera.splice(index, 1);
  38529. this._cameras.splice(index, 1);
  38530. for (var passName in this._renderPasses) {
  38531. this._renderPasses[passName]._decRefCount();
  38532. }
  38533. }
  38534. };
  38535. PostProcessRenderEffect.prototype._enable = function (cameras) {
  38536. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38537. for (var i = 0; i < _cam.length; i++) {
  38538. var camera = _cam[i];
  38539. var cameraName = camera.name;
  38540. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  38541. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  38542. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  38543. }
  38544. }
  38545. for (var passName in this._renderPasses) {
  38546. this._renderPasses[passName]._incRefCount();
  38547. }
  38548. }
  38549. };
  38550. PostProcessRenderEffect.prototype._disable = function (cameras) {
  38551. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38552. for (var i = 0; i < _cam.length; i++) {
  38553. var camera = _cam[i];
  38554. var cameraName = camera.Name;
  38555. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  38556. for (var passName in this._renderPasses) {
  38557. this._renderPasses[passName]._decRefCount();
  38558. }
  38559. }
  38560. };
  38561. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  38562. if (this._singleInstance) {
  38563. return this._postProcesses[0];
  38564. }
  38565. else {
  38566. return this._postProcesses[camera.name];
  38567. }
  38568. };
  38569. PostProcessRenderEffect.prototype._linkParameters = function () {
  38570. var _this = this;
  38571. for (var index in this._postProcesses) {
  38572. if (this.applyParameters) {
  38573. this.applyParameters(this._postProcesses[index]);
  38574. }
  38575. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  38576. _this._linkTextures(effect);
  38577. });
  38578. }
  38579. };
  38580. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  38581. for (var renderPassName in this._renderPasses) {
  38582. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  38583. }
  38584. for (var renderEffectName in this._renderEffectAsPasses) {
  38585. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  38586. }
  38587. };
  38588. return PostProcessRenderEffect;
  38589. }());
  38590. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  38591. })(BABYLON || (BABYLON = {}));
  38592. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  38593. var BABYLON;
  38594. (function (BABYLON) {
  38595. var PostProcessRenderPipeline = (function () {
  38596. function PostProcessRenderPipeline(engine, name) {
  38597. this._engine = engine;
  38598. this._name = name;
  38599. this._renderEffects = {};
  38600. this._renderEffectsForIsolatedPass = {};
  38601. this._cameras = [];
  38602. }
  38603. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  38604. get: function () {
  38605. for (var renderEffectName in this._renderEffects) {
  38606. if (!this._renderEffects[renderEffectName].isSupported) {
  38607. return false;
  38608. }
  38609. }
  38610. return true;
  38611. },
  38612. enumerable: true,
  38613. configurable: true
  38614. });
  38615. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  38616. this._renderEffects[renderEffect._name] = renderEffect;
  38617. };
  38618. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  38619. var renderEffects = this._renderEffects[renderEffectName];
  38620. if (!renderEffects) {
  38621. return;
  38622. }
  38623. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  38624. };
  38625. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  38626. var renderEffects = this._renderEffects[renderEffectName];
  38627. if (!renderEffects) {
  38628. return;
  38629. }
  38630. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  38631. };
  38632. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  38633. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38634. var indicesToDelete = [];
  38635. var i;
  38636. for (i = 0; i < _cam.length; i++) {
  38637. var camera = _cam[i];
  38638. var cameraName = camera.name;
  38639. if (this._cameras.indexOf(camera) === -1) {
  38640. this._cameras[cameraName] = camera;
  38641. }
  38642. else if (unique) {
  38643. indicesToDelete.push(i);
  38644. }
  38645. }
  38646. for (i = 0; i < indicesToDelete.length; i++) {
  38647. cameras.splice(indicesToDelete[i], 1);
  38648. }
  38649. for (var renderEffectName in this._renderEffects) {
  38650. this._renderEffects[renderEffectName]._attachCameras(_cam);
  38651. }
  38652. };
  38653. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  38654. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38655. for (var renderEffectName in this._renderEffects) {
  38656. this._renderEffects[renderEffectName]._detachCameras(_cam);
  38657. }
  38658. for (var i = 0; i < _cam.length; i++) {
  38659. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  38660. }
  38661. };
  38662. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  38663. var _this = this;
  38664. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38665. var pass = null;
  38666. var renderEffectName;
  38667. for (renderEffectName in this._renderEffects) {
  38668. pass = this._renderEffects[renderEffectName].getPass(passName);
  38669. if (pass != null) {
  38670. break;
  38671. }
  38672. }
  38673. if (pass === null) {
  38674. return;
  38675. }
  38676. for (renderEffectName in this._renderEffects) {
  38677. this._renderEffects[renderEffectName]._disable(_cam);
  38678. }
  38679. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  38680. for (var i = 0; i < _cam.length; i++) {
  38681. var camera = _cam[i];
  38682. var cameraName = camera.name;
  38683. 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); });
  38684. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  38685. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  38686. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  38687. }
  38688. };
  38689. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  38690. var _this = this;
  38691. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  38692. for (var i = 0; i < _cam.length; i++) {
  38693. var camera = _cam[i];
  38694. var cameraName = camera.name;
  38695. 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); });
  38696. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  38697. }
  38698. for (var renderEffectName in this._renderEffects) {
  38699. this._renderEffects[renderEffectName]._enable(_cam);
  38700. }
  38701. };
  38702. PostProcessRenderPipeline.prototype._update = function () {
  38703. for (var renderEffectName in this._renderEffects) {
  38704. this._renderEffects[renderEffectName]._update();
  38705. }
  38706. for (var i = 0; i < this._cameras.length; i++) {
  38707. var cameraName = this._cameras[i].name;
  38708. if (this._renderEffectsForIsolatedPass[cameraName]) {
  38709. this._renderEffectsForIsolatedPass[cameraName]._update();
  38710. }
  38711. }
  38712. };
  38713. PostProcessRenderPipeline.prototype.dispose = function () {
  38714. // Must be implemented by children
  38715. };
  38716. return PostProcessRenderPipeline;
  38717. }());
  38718. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  38719. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  38720. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  38721. })(BABYLON || (BABYLON = {}));
  38722. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  38723. var BABYLON;
  38724. (function (BABYLON) {
  38725. var PostProcessRenderPipelineManager = (function () {
  38726. function PostProcessRenderPipelineManager() {
  38727. this._renderPipelines = {};
  38728. }
  38729. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  38730. this._renderPipelines[renderPipeline._name] = renderPipeline;
  38731. };
  38732. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  38733. var renderPipeline = this._renderPipelines[renderPipelineName];
  38734. if (!renderPipeline) {
  38735. return;
  38736. }
  38737. renderPipeline._attachCameras(cameras, unique);
  38738. };
  38739. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  38740. var renderPipeline = this._renderPipelines[renderPipelineName];
  38741. if (!renderPipeline) {
  38742. return;
  38743. }
  38744. renderPipeline._detachCameras(cameras);
  38745. };
  38746. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38747. var renderPipeline = this._renderPipelines[renderPipelineName];
  38748. if (!renderPipeline) {
  38749. return;
  38750. }
  38751. renderPipeline._enableEffect(renderEffectName, cameras);
  38752. };
  38753. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  38754. var renderPipeline = this._renderPipelines[renderPipelineName];
  38755. if (!renderPipeline) {
  38756. return;
  38757. }
  38758. renderPipeline._disableEffect(renderEffectName, cameras);
  38759. };
  38760. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  38761. var renderPipeline = this._renderPipelines[renderPipelineName];
  38762. if (!renderPipeline) {
  38763. return;
  38764. }
  38765. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  38766. };
  38767. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  38768. var renderPipeline = this._renderPipelines[renderPipelineName];
  38769. if (!renderPipeline) {
  38770. return;
  38771. }
  38772. renderPipeline._disableDisplayOnlyPass(cameras);
  38773. };
  38774. PostProcessRenderPipelineManager.prototype.update = function () {
  38775. for (var renderPipelineName in this._renderPipelines) {
  38776. var pipeline = this._renderPipelines[renderPipelineName];
  38777. if (!pipeline.isSupported) {
  38778. pipeline.dispose();
  38779. delete this._renderPipelines[renderPipelineName];
  38780. }
  38781. else {
  38782. pipeline._update();
  38783. }
  38784. }
  38785. };
  38786. return PostProcessRenderPipelineManager;
  38787. }());
  38788. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  38789. })(BABYLON || (BABYLON = {}));
  38790. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  38791. var BABYLON;
  38792. (function (BABYLON) {
  38793. var BoundingBoxRenderer = (function () {
  38794. function BoundingBoxRenderer(scene) {
  38795. this.frontColor = new BABYLON.Color3(1, 1, 1);
  38796. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  38797. this.showBackLines = true;
  38798. this.renderList = new BABYLON.SmartArray(32);
  38799. this._vertexBuffers = {};
  38800. this._scene = scene;
  38801. }
  38802. BoundingBoxRenderer.prototype._prepareRessources = function () {
  38803. if (this._colorShader) {
  38804. return;
  38805. }
  38806. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  38807. attributes: [BABYLON.VertexBuffer.PositionKind],
  38808. uniforms: ["worldViewProjection", "color"]
  38809. });
  38810. var engine = this._scene.getEngine();
  38811. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  38812. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  38813. 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]);
  38814. };
  38815. BoundingBoxRenderer.prototype.reset = function () {
  38816. this.renderList.reset();
  38817. };
  38818. BoundingBoxRenderer.prototype.render = function () {
  38819. if (this.renderList.length === 0) {
  38820. return;
  38821. }
  38822. this._prepareRessources();
  38823. if (!this._colorShader.isReady()) {
  38824. return;
  38825. }
  38826. var engine = this._scene.getEngine();
  38827. engine.setDepthWrite(false);
  38828. this._colorShader._preBind();
  38829. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38830. var boundingBox = this.renderList.data[boundingBoxIndex];
  38831. var min = boundingBox.minimum;
  38832. var max = boundingBox.maximum;
  38833. var diff = max.subtract(min);
  38834. var median = min.add(diff.scale(0.5));
  38835. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38836. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38837. .multiply(boundingBox.getWorldMatrix());
  38838. // VBOs
  38839. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38840. if (this.showBackLines) {
  38841. // Back
  38842. engine.setDepthFunctionToGreaterOrEqual();
  38843. this._scene.resetCachedMaterial();
  38844. this._colorShader.setColor4("color", this.backColor.toColor4());
  38845. this._colorShader.bind(worldMatrix);
  38846. // Draw order
  38847. engine.draw(false, 0, 24);
  38848. }
  38849. // Front
  38850. engine.setDepthFunctionToLess();
  38851. this._scene.resetCachedMaterial();
  38852. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38853. this._colorShader.bind(worldMatrix);
  38854. // Draw order
  38855. engine.draw(false, 0, 24);
  38856. }
  38857. this._colorShader.unbind();
  38858. engine.setDepthFunctionToLessOrEqual();
  38859. engine.setDepthWrite(true);
  38860. };
  38861. BoundingBoxRenderer.prototype.dispose = function () {
  38862. if (!this._colorShader) {
  38863. return;
  38864. }
  38865. this._colorShader.dispose();
  38866. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38867. if (buffer) {
  38868. buffer.dispose();
  38869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38870. }
  38871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38872. };
  38873. return BoundingBoxRenderer;
  38874. }());
  38875. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38876. })(BABYLON || (BABYLON = {}));
  38877. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38878. var BABYLON;
  38879. (function (BABYLON) {
  38880. var Condition = (function () {
  38881. function Condition(actionManager) {
  38882. this._actionManager = actionManager;
  38883. }
  38884. Condition.prototype.isValid = function () {
  38885. return true;
  38886. };
  38887. Condition.prototype._getProperty = function (propertyPath) {
  38888. return this._actionManager._getProperty(propertyPath);
  38889. };
  38890. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38891. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38892. };
  38893. Condition.prototype.serialize = function () {
  38894. };
  38895. Condition.prototype._serialize = function (serializedCondition) {
  38896. return {
  38897. type: 2,
  38898. children: [],
  38899. name: serializedCondition.name,
  38900. properties: serializedCondition.properties
  38901. };
  38902. };
  38903. return Condition;
  38904. }());
  38905. BABYLON.Condition = Condition;
  38906. var ValueCondition = (function (_super) {
  38907. __extends(ValueCondition, _super);
  38908. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38909. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38910. var _this = _super.call(this, actionManager) || this;
  38911. _this.propertyPath = propertyPath;
  38912. _this.value = value;
  38913. _this.operator = operator;
  38914. _this._target = target;
  38915. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38916. _this._property = _this._getProperty(_this.propertyPath);
  38917. return _this;
  38918. }
  38919. Object.defineProperty(ValueCondition, "IsEqual", {
  38920. get: function () {
  38921. return ValueCondition._IsEqual;
  38922. },
  38923. enumerable: true,
  38924. configurable: true
  38925. });
  38926. Object.defineProperty(ValueCondition, "IsDifferent", {
  38927. get: function () {
  38928. return ValueCondition._IsDifferent;
  38929. },
  38930. enumerable: true,
  38931. configurable: true
  38932. });
  38933. Object.defineProperty(ValueCondition, "IsGreater", {
  38934. get: function () {
  38935. return ValueCondition._IsGreater;
  38936. },
  38937. enumerable: true,
  38938. configurable: true
  38939. });
  38940. Object.defineProperty(ValueCondition, "IsLesser", {
  38941. get: function () {
  38942. return ValueCondition._IsLesser;
  38943. },
  38944. enumerable: true,
  38945. configurable: true
  38946. });
  38947. // Methods
  38948. ValueCondition.prototype.isValid = function () {
  38949. switch (this.operator) {
  38950. case ValueCondition.IsGreater:
  38951. return this._effectiveTarget[this._property] > this.value;
  38952. case ValueCondition.IsLesser:
  38953. return this._effectiveTarget[this._property] < this.value;
  38954. case ValueCondition.IsEqual:
  38955. case ValueCondition.IsDifferent:
  38956. var check;
  38957. if (this.value.equals) {
  38958. check = this.value.equals(this._effectiveTarget[this._property]);
  38959. }
  38960. else {
  38961. check = this.value === this._effectiveTarget[this._property];
  38962. }
  38963. return this.operator === ValueCondition.IsEqual ? check : !check;
  38964. }
  38965. return false;
  38966. };
  38967. ValueCondition.prototype.serialize = function () {
  38968. return this._serialize({
  38969. name: "ValueCondition",
  38970. properties: [
  38971. BABYLON.Action._GetTargetProperty(this._target),
  38972. { name: "propertyPath", value: this.propertyPath },
  38973. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38974. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38975. ]
  38976. });
  38977. };
  38978. ValueCondition.GetOperatorName = function (operator) {
  38979. switch (operator) {
  38980. case ValueCondition._IsEqual: return "IsEqual";
  38981. case ValueCondition._IsDifferent: return "IsDifferent";
  38982. case ValueCondition._IsGreater: return "IsGreater";
  38983. case ValueCondition._IsLesser: return "IsLesser";
  38984. default: return "";
  38985. }
  38986. };
  38987. return ValueCondition;
  38988. }(Condition));
  38989. // Statics
  38990. ValueCondition._IsEqual = 0;
  38991. ValueCondition._IsDifferent = 1;
  38992. ValueCondition._IsGreater = 2;
  38993. ValueCondition._IsLesser = 3;
  38994. BABYLON.ValueCondition = ValueCondition;
  38995. var PredicateCondition = (function (_super) {
  38996. __extends(PredicateCondition, _super);
  38997. function PredicateCondition(actionManager, predicate) {
  38998. var _this = _super.call(this, actionManager) || this;
  38999. _this.predicate = predicate;
  39000. return _this;
  39001. }
  39002. PredicateCondition.prototype.isValid = function () {
  39003. return this.predicate();
  39004. };
  39005. return PredicateCondition;
  39006. }(Condition));
  39007. BABYLON.PredicateCondition = PredicateCondition;
  39008. var StateCondition = (function (_super) {
  39009. __extends(StateCondition, _super);
  39010. function StateCondition(actionManager, target, value) {
  39011. var _this = _super.call(this, actionManager) || this;
  39012. _this.value = value;
  39013. _this._target = target;
  39014. return _this;
  39015. }
  39016. // Methods
  39017. StateCondition.prototype.isValid = function () {
  39018. return this._target.state === this.value;
  39019. };
  39020. StateCondition.prototype.serialize = function () {
  39021. return this._serialize({
  39022. name: "StateCondition",
  39023. properties: [
  39024. BABYLON.Action._GetTargetProperty(this._target),
  39025. { name: "value", value: this.value }
  39026. ]
  39027. });
  39028. };
  39029. return StateCondition;
  39030. }(Condition));
  39031. BABYLON.StateCondition = StateCondition;
  39032. })(BABYLON || (BABYLON = {}));
  39033. //# sourceMappingURL=babylon.condition.js.map
  39034. var BABYLON;
  39035. (function (BABYLON) {
  39036. var Action = (function () {
  39037. function Action(triggerOptions, condition) {
  39038. this.triggerOptions = triggerOptions;
  39039. if (triggerOptions.parameter) {
  39040. this.trigger = triggerOptions.trigger;
  39041. this._triggerParameter = triggerOptions.parameter;
  39042. }
  39043. else {
  39044. this.trigger = triggerOptions;
  39045. }
  39046. this._nextActiveAction = this;
  39047. this._condition = condition;
  39048. }
  39049. // Methods
  39050. Action.prototype._prepare = function () {
  39051. };
  39052. Action.prototype.getTriggerParameter = function () {
  39053. return this._triggerParameter;
  39054. };
  39055. Action.prototype._executeCurrent = function (evt) {
  39056. if (this._nextActiveAction._condition) {
  39057. var condition = this._nextActiveAction._condition;
  39058. var currentRenderId = this._actionManager.getScene().getRenderId();
  39059. // We cache the current evaluation for the current frame
  39060. if (condition._evaluationId === currentRenderId) {
  39061. if (!condition._currentResult) {
  39062. return;
  39063. }
  39064. }
  39065. else {
  39066. condition._evaluationId = currentRenderId;
  39067. if (!condition.isValid()) {
  39068. condition._currentResult = false;
  39069. return;
  39070. }
  39071. condition._currentResult = true;
  39072. }
  39073. }
  39074. this._nextActiveAction.execute(evt);
  39075. this.skipToNextActiveAction();
  39076. };
  39077. Action.prototype.execute = function (evt) {
  39078. };
  39079. Action.prototype.skipToNextActiveAction = function () {
  39080. if (this._nextActiveAction._child) {
  39081. if (!this._nextActiveAction._child._actionManager) {
  39082. this._nextActiveAction._child._actionManager = this._actionManager;
  39083. }
  39084. this._nextActiveAction = this._nextActiveAction._child;
  39085. }
  39086. else {
  39087. this._nextActiveAction = this;
  39088. }
  39089. };
  39090. Action.prototype.then = function (action) {
  39091. this._child = action;
  39092. action._actionManager = this._actionManager;
  39093. action._prepare();
  39094. return action;
  39095. };
  39096. Action.prototype._getProperty = function (propertyPath) {
  39097. return this._actionManager._getProperty(propertyPath);
  39098. };
  39099. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  39100. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39101. };
  39102. Action.prototype.serialize = function (parent) {
  39103. };
  39104. // Called by BABYLON.Action objects in serialize(...). Internal use
  39105. Action.prototype._serialize = function (serializedAction, parent) {
  39106. var serializationObject = {
  39107. type: 1,
  39108. children: [],
  39109. name: serializedAction.name,
  39110. properties: serializedAction.properties || []
  39111. };
  39112. // Serialize child
  39113. if (this._child) {
  39114. this._child.serialize(serializationObject);
  39115. }
  39116. // Check if "this" has a condition
  39117. if (this._condition) {
  39118. var serializedCondition = this._condition.serialize();
  39119. serializedCondition.children.push(serializationObject);
  39120. if (parent) {
  39121. parent.children.push(serializedCondition);
  39122. }
  39123. return serializedCondition;
  39124. }
  39125. if (parent) {
  39126. parent.children.push(serializationObject);
  39127. }
  39128. return serializationObject;
  39129. };
  39130. return Action;
  39131. }());
  39132. Action._SerializeValueAsString = function (value) {
  39133. if (typeof value === "number") {
  39134. return value.toString();
  39135. }
  39136. if (typeof value === "boolean") {
  39137. return value ? "true" : "false";
  39138. }
  39139. if (value instanceof BABYLON.Vector2) {
  39140. return value.x + ", " + value.y;
  39141. }
  39142. if (value instanceof BABYLON.Vector3) {
  39143. return value.x + ", " + value.y + ", " + value.z;
  39144. }
  39145. if (value instanceof BABYLON.Color3) {
  39146. return value.r + ", " + value.g + ", " + value.b;
  39147. }
  39148. if (value instanceof BABYLON.Color4) {
  39149. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  39150. }
  39151. return value; // string
  39152. };
  39153. Action._GetTargetProperty = function (target) {
  39154. return {
  39155. name: "target",
  39156. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  39157. : target instanceof BABYLON.Light ? "LightProperties"
  39158. : target instanceof BABYLON.Camera ? "CameraProperties"
  39159. : "SceneProperties",
  39160. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  39161. };
  39162. };
  39163. BABYLON.Action = Action;
  39164. })(BABYLON || (BABYLON = {}));
  39165. //# sourceMappingURL=babylon.action.js.map
  39166. var BABYLON;
  39167. (function (BABYLON) {
  39168. /**
  39169. * ActionEvent is the event beint sent when an action is triggered.
  39170. */
  39171. var ActionEvent = (function () {
  39172. /**
  39173. * @constructor
  39174. * @param source The mesh or sprite that triggered the action.
  39175. * @param pointerX The X mouse cursor position at the time of the event
  39176. * @param pointerY The Y mouse cursor position at the time of the event
  39177. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  39178. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  39179. */
  39180. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  39181. this.source = source;
  39182. this.pointerX = pointerX;
  39183. this.pointerY = pointerY;
  39184. this.meshUnderPointer = meshUnderPointer;
  39185. this.sourceEvent = sourceEvent;
  39186. this.additionalData = additionalData;
  39187. }
  39188. /**
  39189. * Helper function to auto-create an ActionEvent from a source mesh.
  39190. * @param source The source mesh that triggered the event
  39191. * @param evt {Event} The original (browser) event
  39192. */
  39193. ActionEvent.CreateNew = function (source, evt, additionalData) {
  39194. var scene = source.getScene();
  39195. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39196. };
  39197. /**
  39198. * Helper function to auto-create an ActionEvent from a source mesh.
  39199. * @param source The source sprite that triggered the event
  39200. * @param scene Scene associated with the sprite
  39201. * @param evt {Event} The original (browser) event
  39202. */
  39203. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  39204. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39205. };
  39206. /**
  39207. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  39208. * @param scene the scene where the event occurred
  39209. * @param evt {Event} The original (browser) event
  39210. */
  39211. ActionEvent.CreateNewFromScene = function (scene, evt) {
  39212. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  39213. };
  39214. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  39215. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  39216. };
  39217. return ActionEvent;
  39218. }());
  39219. BABYLON.ActionEvent = ActionEvent;
  39220. /**
  39221. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  39222. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  39223. */
  39224. var ActionManager = (function () {
  39225. function ActionManager(scene) {
  39226. // Members
  39227. this.actions = new Array();
  39228. this.hoverCursor = '';
  39229. this._scene = scene;
  39230. scene._actionManagers.push(this);
  39231. }
  39232. Object.defineProperty(ActionManager, "NothingTrigger", {
  39233. get: function () {
  39234. return ActionManager._NothingTrigger;
  39235. },
  39236. enumerable: true,
  39237. configurable: true
  39238. });
  39239. Object.defineProperty(ActionManager, "OnPickTrigger", {
  39240. get: function () {
  39241. return ActionManager._OnPickTrigger;
  39242. },
  39243. enumerable: true,
  39244. configurable: true
  39245. });
  39246. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  39247. get: function () {
  39248. return ActionManager._OnLeftPickTrigger;
  39249. },
  39250. enumerable: true,
  39251. configurable: true
  39252. });
  39253. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  39254. get: function () {
  39255. return ActionManager._OnRightPickTrigger;
  39256. },
  39257. enumerable: true,
  39258. configurable: true
  39259. });
  39260. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  39261. get: function () {
  39262. return ActionManager._OnCenterPickTrigger;
  39263. },
  39264. enumerable: true,
  39265. configurable: true
  39266. });
  39267. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  39268. get: function () {
  39269. return ActionManager._OnPickDownTrigger;
  39270. },
  39271. enumerable: true,
  39272. configurable: true
  39273. });
  39274. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  39275. get: function () {
  39276. return ActionManager._OnPickUpTrigger;
  39277. },
  39278. enumerable: true,
  39279. configurable: true
  39280. });
  39281. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  39282. /// This trigger will only be raised if you also declared a OnPickDown
  39283. get: function () {
  39284. return ActionManager._OnPickOutTrigger;
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  39290. get: function () {
  39291. return ActionManager._OnLongPressTrigger;
  39292. },
  39293. enumerable: true,
  39294. configurable: true
  39295. });
  39296. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  39297. get: function () {
  39298. return ActionManager._OnPointerOverTrigger;
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  39304. get: function () {
  39305. return ActionManager._OnPointerOutTrigger;
  39306. },
  39307. enumerable: true,
  39308. configurable: true
  39309. });
  39310. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  39311. get: function () {
  39312. return ActionManager._OnEveryFrameTrigger;
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  39318. get: function () {
  39319. return ActionManager._OnIntersectionEnterTrigger;
  39320. },
  39321. enumerable: true,
  39322. configurable: true
  39323. });
  39324. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  39325. get: function () {
  39326. return ActionManager._OnIntersectionExitTrigger;
  39327. },
  39328. enumerable: true,
  39329. configurable: true
  39330. });
  39331. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  39332. get: function () {
  39333. return ActionManager._OnKeyDownTrigger;
  39334. },
  39335. enumerable: true,
  39336. configurable: true
  39337. });
  39338. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  39339. get: function () {
  39340. return ActionManager._OnKeyUpTrigger;
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. // Methods
  39346. ActionManager.prototype.dispose = function () {
  39347. var index = this._scene._actionManagers.indexOf(this);
  39348. if (index > -1) {
  39349. this._scene._actionManagers.splice(index, 1);
  39350. }
  39351. };
  39352. ActionManager.prototype.getScene = function () {
  39353. return this._scene;
  39354. };
  39355. /**
  39356. * Does this action manager handles actions of any of the given triggers
  39357. * @param {number[]} triggers - the triggers to be tested
  39358. * @return {boolean} whether one (or more) of the triggers is handeled
  39359. */
  39360. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  39361. for (var index = 0; index < this.actions.length; index++) {
  39362. var action = this.actions[index];
  39363. if (triggers.indexOf(action.trigger) > -1) {
  39364. return true;
  39365. }
  39366. }
  39367. return false;
  39368. };
  39369. /**
  39370. * Does this action manager handles actions of a given trigger
  39371. * @param {number} trigger - the trigger to be tested
  39372. * @return {boolean} whether the trigger is handeled
  39373. */
  39374. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  39375. for (var index = 0; index < this.actions.length; index++) {
  39376. var action = this.actions[index];
  39377. if (action.trigger === trigger) {
  39378. return true;
  39379. }
  39380. }
  39381. return false;
  39382. };
  39383. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  39384. /**
  39385. * Does this action manager has pointer triggers
  39386. * @return {boolean} whether or not it has pointer triggers
  39387. */
  39388. get: function () {
  39389. for (var index = 0; index < this.actions.length; index++) {
  39390. var action = this.actions[index];
  39391. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  39392. return true;
  39393. }
  39394. }
  39395. return false;
  39396. },
  39397. enumerable: true,
  39398. configurable: true
  39399. });
  39400. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  39401. /**
  39402. * Does this action manager has pick triggers
  39403. * @return {boolean} whether or not it has pick triggers
  39404. */
  39405. get: function () {
  39406. for (var index = 0; index < this.actions.length; index++) {
  39407. var action = this.actions[index];
  39408. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  39409. return true;
  39410. }
  39411. }
  39412. return false;
  39413. },
  39414. enumerable: true,
  39415. configurable: true
  39416. });
  39417. /**
  39418. * Registers an action to this action manager
  39419. * @param {BABYLON.Action} action - the action to be registered
  39420. * @return {BABYLON.Action} the action amended (prepared) after registration
  39421. */
  39422. ActionManager.prototype.registerAction = function (action) {
  39423. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  39424. if (this.getScene().actionManager !== this) {
  39425. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  39426. return null;
  39427. }
  39428. }
  39429. this.actions.push(action);
  39430. action._actionManager = this;
  39431. action._prepare();
  39432. return action;
  39433. };
  39434. /**
  39435. * Process a specific trigger
  39436. * @param {number} trigger - the trigger to process
  39437. * @param evt {BABYLON.ActionEvent} the event details to be processed
  39438. */
  39439. ActionManager.prototype.processTrigger = function (trigger, evt) {
  39440. for (var index = 0; index < this.actions.length; index++) {
  39441. var action = this.actions[index];
  39442. if (action.trigger === trigger) {
  39443. if (trigger === ActionManager.OnKeyUpTrigger
  39444. || trigger === ActionManager.OnKeyDownTrigger) {
  39445. var parameter = action.getTriggerParameter();
  39446. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  39447. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  39448. var actualkey = String.fromCharCode(unicode).toLowerCase();
  39449. if (actualkey !== parameter.toLowerCase()) {
  39450. continue;
  39451. }
  39452. }
  39453. }
  39454. action._executeCurrent(evt);
  39455. }
  39456. }
  39457. };
  39458. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  39459. var properties = propertyPath.split(".");
  39460. for (var index = 0; index < properties.length - 1; index++) {
  39461. target = target[properties[index]];
  39462. }
  39463. return target;
  39464. };
  39465. ActionManager.prototype._getProperty = function (propertyPath) {
  39466. var properties = propertyPath.split(".");
  39467. return properties[properties.length - 1];
  39468. };
  39469. ActionManager.prototype.serialize = function (name) {
  39470. var root = {
  39471. children: [],
  39472. name: name,
  39473. type: 3,
  39474. properties: [] // Empty for root but required
  39475. };
  39476. for (var i = 0; i < this.actions.length; i++) {
  39477. var triggerObject = {
  39478. type: 0,
  39479. children: [],
  39480. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  39481. properties: []
  39482. };
  39483. var triggerOptions = this.actions[i].triggerOptions;
  39484. if (triggerOptions && typeof triggerOptions !== "number") {
  39485. if (triggerOptions.parameter instanceof BABYLON.Node) {
  39486. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  39487. }
  39488. else {
  39489. var parameter = {};
  39490. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  39491. if (triggerOptions.parameter.mesh) {
  39492. parameter._meshId = triggerOptions.parameter.mesh.id;
  39493. }
  39494. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  39495. }
  39496. }
  39497. // Serialize child action, recursively
  39498. this.actions[i].serialize(triggerObject);
  39499. // Add serialized trigger
  39500. root.children.push(triggerObject);
  39501. }
  39502. return root;
  39503. };
  39504. ActionManager.Parse = function (parsedActions, object, scene) {
  39505. var actionManager = new BABYLON.ActionManager(scene);
  39506. if (object === null)
  39507. scene.actionManager = actionManager;
  39508. else
  39509. object.actionManager = actionManager;
  39510. // instanciate a new object
  39511. var instanciate = function (name, params) {
  39512. var newInstance = Object.create(BABYLON[name].prototype);
  39513. newInstance.constructor.apply(newInstance, params);
  39514. return newInstance;
  39515. };
  39516. var parseParameter = function (name, value, target, propertyPath) {
  39517. if (propertyPath === null) {
  39518. // String, boolean or float
  39519. var floatValue = parseFloat(value);
  39520. if (value === "true" || value === "false")
  39521. return value === "true";
  39522. else
  39523. return isNaN(floatValue) ? value : floatValue;
  39524. }
  39525. var effectiveTarget = propertyPath.split(".");
  39526. var values = value.split(",");
  39527. // Get effective Target
  39528. for (var i = 0; i < effectiveTarget.length; i++) {
  39529. target = target[effectiveTarget[i]];
  39530. }
  39531. // Return appropriate value with its type
  39532. if (typeof (target) === "boolean")
  39533. return values[0] === "true";
  39534. if (typeof (target) === "string")
  39535. return values[0];
  39536. // Parameters with multiple values such as Vector3 etc.
  39537. var split = new Array();
  39538. for (var i = 0; i < values.length; i++)
  39539. split.push(parseFloat(values[i]));
  39540. if (target instanceof BABYLON.Vector3)
  39541. return BABYLON.Vector3.FromArray(split);
  39542. if (target instanceof BABYLON.Vector4)
  39543. return BABYLON.Vector4.FromArray(split);
  39544. if (target instanceof BABYLON.Color3)
  39545. return BABYLON.Color3.FromArray(split);
  39546. if (target instanceof BABYLON.Color4)
  39547. return BABYLON.Color4.FromArray(split);
  39548. return parseFloat(values[0]);
  39549. };
  39550. // traverse graph per trigger
  39551. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  39552. if (combineArray === void 0) { combineArray = null; }
  39553. if (parsedAction.detached)
  39554. return;
  39555. var parameters = new Array();
  39556. var target = null;
  39557. var propertyPath = null;
  39558. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  39559. // Parameters
  39560. if (parsedAction.type === 2)
  39561. parameters.push(actionManager);
  39562. else
  39563. parameters.push(trigger);
  39564. if (combine) {
  39565. var actions = new Array();
  39566. for (var j = 0; j < parsedAction.combine.length; j++) {
  39567. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  39568. }
  39569. parameters.push(actions);
  39570. }
  39571. else {
  39572. for (var i = 0; i < parsedAction.properties.length; i++) {
  39573. var value = parsedAction.properties[i].value;
  39574. var name = parsedAction.properties[i].name;
  39575. var targetType = parsedAction.properties[i].targetType;
  39576. if (name === "target")
  39577. if (targetType !== null && targetType === "SceneProperties")
  39578. value = target = scene;
  39579. else
  39580. value = target = scene.getNodeByName(value);
  39581. else if (name === "parent")
  39582. value = scene.getNodeByName(value);
  39583. else if (name === "sound")
  39584. value = scene.getSoundByName(value);
  39585. else if (name !== "propertyPath") {
  39586. if (parsedAction.type === 2 && name === "operator")
  39587. value = BABYLON.ValueCondition[value];
  39588. else
  39589. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  39590. }
  39591. else {
  39592. propertyPath = value;
  39593. }
  39594. parameters.push(value);
  39595. }
  39596. }
  39597. if (combineArray === null) {
  39598. parameters.push(condition);
  39599. }
  39600. else {
  39601. parameters.push(null);
  39602. }
  39603. // If interpolate value action
  39604. if (parsedAction.name === "InterpolateValueAction") {
  39605. var param = parameters[parameters.length - 2];
  39606. parameters[parameters.length - 1] = param;
  39607. parameters[parameters.length - 2] = condition;
  39608. }
  39609. // Action or condition(s) and not CombineAction
  39610. var newAction = instanciate(parsedAction.name, parameters);
  39611. if (newAction instanceof BABYLON.Condition && condition !== null) {
  39612. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  39613. if (action)
  39614. action.then(nothing);
  39615. else
  39616. actionManager.registerAction(nothing);
  39617. action = nothing;
  39618. }
  39619. if (combineArray === null) {
  39620. if (newAction instanceof BABYLON.Condition) {
  39621. condition = newAction;
  39622. newAction = action;
  39623. }
  39624. else {
  39625. condition = null;
  39626. if (action)
  39627. action.then(newAction);
  39628. else
  39629. actionManager.registerAction(newAction);
  39630. }
  39631. }
  39632. else {
  39633. combineArray.push(newAction);
  39634. }
  39635. for (var i = 0; i < parsedAction.children.length; i++)
  39636. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  39637. };
  39638. // triggers
  39639. for (var i = 0; i < parsedActions.children.length; i++) {
  39640. var triggerParams;
  39641. var trigger = parsedActions.children[i];
  39642. if (trigger.properties.length > 0) {
  39643. var param = trigger.properties[0].value;
  39644. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  39645. if (value._meshId) {
  39646. value.mesh = scene.getMeshByID(value._meshId);
  39647. }
  39648. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  39649. }
  39650. else
  39651. triggerParams = BABYLON.ActionManager[trigger.name];
  39652. for (var j = 0; j < trigger.children.length; j++) {
  39653. if (!trigger.detached)
  39654. traverse(trigger.children[j], triggerParams, null, null);
  39655. }
  39656. }
  39657. };
  39658. ActionManager.GetTriggerName = function (trigger) {
  39659. switch (trigger) {
  39660. case 0: return "NothingTrigger";
  39661. case 1: return "OnPickTrigger";
  39662. case 2: return "OnLeftPickTrigger";
  39663. case 3: return "OnRightPickTrigger";
  39664. case 4: return "OnCenterPickTrigger";
  39665. case 5: return "OnPickDownTrigger";
  39666. case 6: return "OnPickUpTrigger";
  39667. case 7: return "OnLongPressTrigger";
  39668. case 8: return "OnPointerOverTrigger";
  39669. case 9: return "OnPointerOutTrigger";
  39670. case 10: return "OnEveryFrameTrigger";
  39671. case 11: return "OnIntersectionEnterTrigger";
  39672. case 12: return "OnIntersectionExitTrigger";
  39673. case 13: return "OnKeyDownTrigger";
  39674. case 14: return "OnKeyUpTrigger";
  39675. case 15: return "OnPickOutTrigger";
  39676. default: return "";
  39677. }
  39678. };
  39679. return ActionManager;
  39680. }());
  39681. // Statics
  39682. ActionManager._NothingTrigger = 0;
  39683. ActionManager._OnPickTrigger = 1;
  39684. ActionManager._OnLeftPickTrigger = 2;
  39685. ActionManager._OnRightPickTrigger = 3;
  39686. ActionManager._OnCenterPickTrigger = 4;
  39687. ActionManager._OnPickDownTrigger = 5;
  39688. ActionManager._OnPickUpTrigger = 6;
  39689. ActionManager._OnLongPressTrigger = 7;
  39690. ActionManager._OnPointerOverTrigger = 8;
  39691. ActionManager._OnPointerOutTrigger = 9;
  39692. ActionManager._OnEveryFrameTrigger = 10;
  39693. ActionManager._OnIntersectionEnterTrigger = 11;
  39694. ActionManager._OnIntersectionExitTrigger = 12;
  39695. ActionManager._OnKeyDownTrigger = 13;
  39696. ActionManager._OnKeyUpTrigger = 14;
  39697. ActionManager._OnPickOutTrigger = 15;
  39698. ActionManager.DragMovementThreshold = 10; // in pixels
  39699. ActionManager.LongPressDelay = 500; // in milliseconds
  39700. BABYLON.ActionManager = ActionManager;
  39701. })(BABYLON || (BABYLON = {}));
  39702. //# sourceMappingURL=babylon.actionManager.js.map
  39703. var BABYLON;
  39704. (function (BABYLON) {
  39705. var InterpolateValueAction = (function (_super) {
  39706. __extends(InterpolateValueAction, _super);
  39707. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  39708. if (duration === void 0) { duration = 1000; }
  39709. var _this = _super.call(this, triggerOptions, condition) || this;
  39710. _this.propertyPath = propertyPath;
  39711. _this.value = value;
  39712. _this.duration = duration;
  39713. _this.stopOtherAnimations = stopOtherAnimations;
  39714. _this.onInterpolationDone = onInterpolationDone;
  39715. _this._target = _this._effectiveTarget = target;
  39716. return _this;
  39717. }
  39718. InterpolateValueAction.prototype._prepare = function () {
  39719. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39720. this._property = this._getProperty(this.propertyPath);
  39721. };
  39722. InterpolateValueAction.prototype.execute = function () {
  39723. var scene = this._actionManager.getScene();
  39724. var keys = [
  39725. {
  39726. frame: 0,
  39727. value: this._effectiveTarget[this._property]
  39728. }, {
  39729. frame: 100,
  39730. value: this.value
  39731. }
  39732. ];
  39733. var dataType;
  39734. if (typeof this.value === "number") {
  39735. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  39736. }
  39737. else if (this.value instanceof BABYLON.Color3) {
  39738. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  39739. }
  39740. else if (this.value instanceof BABYLON.Vector3) {
  39741. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  39742. }
  39743. else if (this.value instanceof BABYLON.Matrix) {
  39744. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  39745. }
  39746. else if (this.value instanceof BABYLON.Quaternion) {
  39747. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  39748. }
  39749. else {
  39750. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  39751. return;
  39752. }
  39753. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  39754. animation.setKeys(keys);
  39755. if (this.stopOtherAnimations) {
  39756. scene.stopAnimation(this._effectiveTarget);
  39757. }
  39758. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  39759. };
  39760. InterpolateValueAction.prototype.serialize = function (parent) {
  39761. return _super.prototype._serialize.call(this, {
  39762. name: "InterpolateValueAction",
  39763. properties: [
  39764. BABYLON.Action._GetTargetProperty(this._target),
  39765. { name: "propertyPath", value: this.propertyPath },
  39766. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39767. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  39768. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  39769. ]
  39770. }, parent);
  39771. };
  39772. return InterpolateValueAction;
  39773. }(BABYLON.Action));
  39774. BABYLON.InterpolateValueAction = InterpolateValueAction;
  39775. })(BABYLON || (BABYLON = {}));
  39776. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  39777. var BABYLON;
  39778. (function (BABYLON) {
  39779. var SwitchBooleanAction = (function (_super) {
  39780. __extends(SwitchBooleanAction, _super);
  39781. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  39782. var _this = _super.call(this, triggerOptions, condition) || this;
  39783. _this.propertyPath = propertyPath;
  39784. _this._target = _this._effectiveTarget = target;
  39785. return _this;
  39786. }
  39787. SwitchBooleanAction.prototype._prepare = function () {
  39788. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39789. this._property = this._getProperty(this.propertyPath);
  39790. };
  39791. SwitchBooleanAction.prototype.execute = function () {
  39792. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  39793. };
  39794. SwitchBooleanAction.prototype.serialize = function (parent) {
  39795. return _super.prototype._serialize.call(this, {
  39796. name: "SwitchBooleanAction",
  39797. properties: [
  39798. BABYLON.Action._GetTargetProperty(this._target),
  39799. { name: "propertyPath", value: this.propertyPath }
  39800. ]
  39801. }, parent);
  39802. };
  39803. return SwitchBooleanAction;
  39804. }(BABYLON.Action));
  39805. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39806. var SetStateAction = (function (_super) {
  39807. __extends(SetStateAction, _super);
  39808. function SetStateAction(triggerOptions, target, value, condition) {
  39809. var _this = _super.call(this, triggerOptions, condition) || this;
  39810. _this.value = value;
  39811. _this._target = target;
  39812. return _this;
  39813. }
  39814. SetStateAction.prototype.execute = function () {
  39815. this._target.state = this.value;
  39816. };
  39817. SetStateAction.prototype.serialize = function (parent) {
  39818. return _super.prototype._serialize.call(this, {
  39819. name: "SetStateAction",
  39820. properties: [
  39821. BABYLON.Action._GetTargetProperty(this._target),
  39822. { name: "value", value: this.value }
  39823. ]
  39824. }, parent);
  39825. };
  39826. return SetStateAction;
  39827. }(BABYLON.Action));
  39828. BABYLON.SetStateAction = SetStateAction;
  39829. var SetValueAction = (function (_super) {
  39830. __extends(SetValueAction, _super);
  39831. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39832. var _this = _super.call(this, triggerOptions, condition) || this;
  39833. _this.propertyPath = propertyPath;
  39834. _this.value = value;
  39835. _this._target = _this._effectiveTarget = target;
  39836. return _this;
  39837. }
  39838. SetValueAction.prototype._prepare = function () {
  39839. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39840. this._property = this._getProperty(this.propertyPath);
  39841. };
  39842. SetValueAction.prototype.execute = function () {
  39843. this._effectiveTarget[this._property] = this.value;
  39844. if (this._target.markAsDirty) {
  39845. this._target.markAsDirty(this._property);
  39846. }
  39847. };
  39848. SetValueAction.prototype.serialize = function (parent) {
  39849. return _super.prototype._serialize.call(this, {
  39850. name: "SetValueAction",
  39851. properties: [
  39852. BABYLON.Action._GetTargetProperty(this._target),
  39853. { name: "propertyPath", value: this.propertyPath },
  39854. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39855. ]
  39856. }, parent);
  39857. };
  39858. return SetValueAction;
  39859. }(BABYLON.Action));
  39860. BABYLON.SetValueAction = SetValueAction;
  39861. var IncrementValueAction = (function (_super) {
  39862. __extends(IncrementValueAction, _super);
  39863. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39864. var _this = _super.call(this, triggerOptions, condition) || this;
  39865. _this.propertyPath = propertyPath;
  39866. _this.value = value;
  39867. _this._target = _this._effectiveTarget = target;
  39868. return _this;
  39869. }
  39870. IncrementValueAction.prototype._prepare = function () {
  39871. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39872. this._property = this._getProperty(this.propertyPath);
  39873. if (typeof this._effectiveTarget[this._property] !== "number") {
  39874. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39875. }
  39876. };
  39877. IncrementValueAction.prototype.execute = function () {
  39878. this._effectiveTarget[this._property] += this.value;
  39879. if (this._target.markAsDirty) {
  39880. this._target.markAsDirty(this._property);
  39881. }
  39882. };
  39883. IncrementValueAction.prototype.serialize = function (parent) {
  39884. return _super.prototype._serialize.call(this, {
  39885. name: "IncrementValueAction",
  39886. properties: [
  39887. BABYLON.Action._GetTargetProperty(this._target),
  39888. { name: "propertyPath", value: this.propertyPath },
  39889. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39890. ]
  39891. }, parent);
  39892. };
  39893. return IncrementValueAction;
  39894. }(BABYLON.Action));
  39895. BABYLON.IncrementValueAction = IncrementValueAction;
  39896. var PlayAnimationAction = (function (_super) {
  39897. __extends(PlayAnimationAction, _super);
  39898. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39899. var _this = _super.call(this, triggerOptions, condition) || this;
  39900. _this.from = from;
  39901. _this.to = to;
  39902. _this.loop = loop;
  39903. _this._target = target;
  39904. return _this;
  39905. }
  39906. PlayAnimationAction.prototype._prepare = function () {
  39907. };
  39908. PlayAnimationAction.prototype.execute = function () {
  39909. var scene = this._actionManager.getScene();
  39910. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39911. };
  39912. PlayAnimationAction.prototype.serialize = function (parent) {
  39913. return _super.prototype._serialize.call(this, {
  39914. name: "PlayAnimationAction",
  39915. properties: [
  39916. BABYLON.Action._GetTargetProperty(this._target),
  39917. { name: "from", value: String(this.from) },
  39918. { name: "to", value: String(this.to) },
  39919. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39920. ]
  39921. }, parent);
  39922. };
  39923. return PlayAnimationAction;
  39924. }(BABYLON.Action));
  39925. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39926. var StopAnimationAction = (function (_super) {
  39927. __extends(StopAnimationAction, _super);
  39928. function StopAnimationAction(triggerOptions, target, condition) {
  39929. var _this = _super.call(this, triggerOptions, condition) || this;
  39930. _this._target = target;
  39931. return _this;
  39932. }
  39933. StopAnimationAction.prototype._prepare = function () {
  39934. };
  39935. StopAnimationAction.prototype.execute = function () {
  39936. var scene = this._actionManager.getScene();
  39937. scene.stopAnimation(this._target);
  39938. };
  39939. StopAnimationAction.prototype.serialize = function (parent) {
  39940. return _super.prototype._serialize.call(this, {
  39941. name: "StopAnimationAction",
  39942. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39943. }, parent);
  39944. };
  39945. return StopAnimationAction;
  39946. }(BABYLON.Action));
  39947. BABYLON.StopAnimationAction = StopAnimationAction;
  39948. var DoNothingAction = (function (_super) {
  39949. __extends(DoNothingAction, _super);
  39950. function DoNothingAction(triggerOptions, condition) {
  39951. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39952. return _super.call(this, triggerOptions, condition) || this;
  39953. }
  39954. DoNothingAction.prototype.execute = function () {
  39955. };
  39956. DoNothingAction.prototype.serialize = function (parent) {
  39957. return _super.prototype._serialize.call(this, {
  39958. name: "DoNothingAction",
  39959. properties: []
  39960. }, parent);
  39961. };
  39962. return DoNothingAction;
  39963. }(BABYLON.Action));
  39964. BABYLON.DoNothingAction = DoNothingAction;
  39965. var CombineAction = (function (_super) {
  39966. __extends(CombineAction, _super);
  39967. function CombineAction(triggerOptions, children, condition) {
  39968. var _this = _super.call(this, triggerOptions, condition) || this;
  39969. _this.children = children;
  39970. return _this;
  39971. }
  39972. CombineAction.prototype._prepare = function () {
  39973. for (var index = 0; index < this.children.length; index++) {
  39974. this.children[index]._actionManager = this._actionManager;
  39975. this.children[index]._prepare();
  39976. }
  39977. };
  39978. CombineAction.prototype.execute = function (evt) {
  39979. for (var index = 0; index < this.children.length; index++) {
  39980. this.children[index].execute(evt);
  39981. }
  39982. };
  39983. CombineAction.prototype.serialize = function (parent) {
  39984. var serializationObject = _super.prototype._serialize.call(this, {
  39985. name: "CombineAction",
  39986. properties: [],
  39987. combine: []
  39988. }, parent);
  39989. for (var i = 0; i < this.children.length; i++) {
  39990. serializationObject.combine.push(this.children[i].serialize(null));
  39991. }
  39992. return serializationObject;
  39993. };
  39994. return CombineAction;
  39995. }(BABYLON.Action));
  39996. BABYLON.CombineAction = CombineAction;
  39997. var ExecuteCodeAction = (function (_super) {
  39998. __extends(ExecuteCodeAction, _super);
  39999. function ExecuteCodeAction(triggerOptions, func, condition) {
  40000. var _this = _super.call(this, triggerOptions, condition) || this;
  40001. _this.func = func;
  40002. return _this;
  40003. }
  40004. ExecuteCodeAction.prototype.execute = function (evt) {
  40005. this.func(evt);
  40006. };
  40007. return ExecuteCodeAction;
  40008. }(BABYLON.Action));
  40009. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  40010. var SetParentAction = (function (_super) {
  40011. __extends(SetParentAction, _super);
  40012. function SetParentAction(triggerOptions, target, parent, condition) {
  40013. var _this = _super.call(this, triggerOptions, condition) || this;
  40014. _this._target = target;
  40015. _this._parent = parent;
  40016. return _this;
  40017. }
  40018. SetParentAction.prototype._prepare = function () {
  40019. };
  40020. SetParentAction.prototype.execute = function () {
  40021. if (this._target.parent === this._parent) {
  40022. return;
  40023. }
  40024. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  40025. invertParentWorldMatrix.invert();
  40026. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  40027. this._target.parent = this._parent;
  40028. };
  40029. SetParentAction.prototype.serialize = function (parent) {
  40030. return _super.prototype._serialize.call(this, {
  40031. name: "SetParentAction",
  40032. properties: [
  40033. BABYLON.Action._GetTargetProperty(this._target),
  40034. BABYLON.Action._GetTargetProperty(this._parent),
  40035. ]
  40036. }, parent);
  40037. };
  40038. return SetParentAction;
  40039. }(BABYLON.Action));
  40040. BABYLON.SetParentAction = SetParentAction;
  40041. var PlaySoundAction = (function (_super) {
  40042. __extends(PlaySoundAction, _super);
  40043. function PlaySoundAction(triggerOptions, sound, condition) {
  40044. var _this = _super.call(this, triggerOptions, condition) || this;
  40045. _this._sound = sound;
  40046. return _this;
  40047. }
  40048. PlaySoundAction.prototype._prepare = function () {
  40049. };
  40050. PlaySoundAction.prototype.execute = function () {
  40051. if (this._sound !== undefined)
  40052. this._sound.play();
  40053. };
  40054. PlaySoundAction.prototype.serialize = function (parent) {
  40055. return _super.prototype._serialize.call(this, {
  40056. name: "PlaySoundAction",
  40057. properties: [{ name: "sound", value: this._sound.name }]
  40058. }, parent);
  40059. };
  40060. return PlaySoundAction;
  40061. }(BABYLON.Action));
  40062. BABYLON.PlaySoundAction = PlaySoundAction;
  40063. var StopSoundAction = (function (_super) {
  40064. __extends(StopSoundAction, _super);
  40065. function StopSoundAction(triggerOptions, sound, condition) {
  40066. var _this = _super.call(this, triggerOptions, condition) || this;
  40067. _this._sound = sound;
  40068. return _this;
  40069. }
  40070. StopSoundAction.prototype._prepare = function () {
  40071. };
  40072. StopSoundAction.prototype.execute = function () {
  40073. if (this._sound !== undefined)
  40074. this._sound.stop();
  40075. };
  40076. StopSoundAction.prototype.serialize = function (parent) {
  40077. return _super.prototype._serialize.call(this, {
  40078. name: "StopSoundAction",
  40079. properties: [{ name: "sound", value: this._sound.name }]
  40080. }, parent);
  40081. };
  40082. return StopSoundAction;
  40083. }(BABYLON.Action));
  40084. BABYLON.StopSoundAction = StopSoundAction;
  40085. })(BABYLON || (BABYLON = {}));
  40086. //# sourceMappingURL=babylon.directActions.js.map
  40087. var BABYLON;
  40088. (function (BABYLON) {
  40089. var Geometry = (function () {
  40090. function Geometry(id, scene, vertexData, updatable, mesh) {
  40091. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40092. this._totalVertices = 0;
  40093. this._isDisposed = false;
  40094. this.id = id;
  40095. this._engine = scene.getEngine();
  40096. this._meshes = [];
  40097. this._scene = scene;
  40098. //Init vertex buffer cache
  40099. this._vertexBuffers = {};
  40100. this._indices = [];
  40101. // vertexData
  40102. if (vertexData) {
  40103. this.setAllVerticesData(vertexData, updatable);
  40104. }
  40105. else {
  40106. this._totalVertices = 0;
  40107. this._indices = [];
  40108. }
  40109. if (this._engine.getCaps().vertexArrayObject) {
  40110. this._vertexArrayObjects = {};
  40111. }
  40112. // applyToMesh
  40113. if (mesh) {
  40114. if (mesh instanceof BABYLON.LinesMesh) {
  40115. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40116. this.updateExtend();
  40117. }
  40118. this.applyToMesh(mesh);
  40119. mesh.computeWorldMatrix(true);
  40120. }
  40121. }
  40122. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40123. /**
  40124. * 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
  40125. * @returns The Bias Vector
  40126. */
  40127. get: function () {
  40128. return this._boundingBias;
  40129. },
  40130. set: function (value) {
  40131. if (this._boundingBias && this._boundingBias.equals(value)) {
  40132. return;
  40133. }
  40134. this._boundingBias = value.clone();
  40135. this.updateBoundingInfo(true, null);
  40136. },
  40137. enumerable: true,
  40138. configurable: true
  40139. });
  40140. Object.defineProperty(Geometry.prototype, "extend", {
  40141. get: function () {
  40142. return this._extend;
  40143. },
  40144. enumerable: true,
  40145. configurable: true
  40146. });
  40147. Geometry.prototype.getScene = function () {
  40148. return this._scene;
  40149. };
  40150. Geometry.prototype.getEngine = function () {
  40151. return this._engine;
  40152. };
  40153. Geometry.prototype.isReady = function () {
  40154. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40155. };
  40156. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40157. get: function () {
  40158. for (var index = 0; index < this._meshes.length; index++) {
  40159. if (!this._meshes[index].doNotSerialize) {
  40160. return false;
  40161. }
  40162. }
  40163. return true;
  40164. },
  40165. enumerable: true,
  40166. configurable: true
  40167. });
  40168. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40169. vertexData.applyToGeometry(this, updatable);
  40170. this.notifyUpdate();
  40171. };
  40172. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40173. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40174. this.setVerticesBuffer(buffer);
  40175. };
  40176. Geometry.prototype.setVerticesBuffer = function (buffer) {
  40177. var kind = buffer.getKind();
  40178. if (this._vertexBuffers[kind]) {
  40179. this._vertexBuffers[kind].dispose();
  40180. }
  40181. this._vertexBuffers[kind] = buffer;
  40182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40183. var data = buffer.getData();
  40184. var stride = buffer.getStrideSize();
  40185. this._totalVertices = data.length / stride;
  40186. this.updateExtend(data, stride);
  40187. var meshes = this._meshes;
  40188. var numOfMeshes = meshes.length;
  40189. for (var index = 0; index < numOfMeshes; index++) {
  40190. var mesh = meshes[index];
  40191. mesh._resetPointsArrayCache();
  40192. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40193. mesh._createGlobalSubMesh();
  40194. mesh.computeWorldMatrix(true);
  40195. }
  40196. }
  40197. this.notifyUpdate(kind);
  40198. if (this._vertexArrayObjects) {
  40199. this._disposeVertexArrayObjects();
  40200. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40201. }
  40202. };
  40203. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  40204. var vertexBuffer = this.getVertexBuffer(kind);
  40205. if (!vertexBuffer) {
  40206. return;
  40207. }
  40208. vertexBuffer.updateDirectly(data, offset);
  40209. this.notifyUpdate(kind);
  40210. };
  40211. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40212. var vertexBuffer = this.getVertexBuffer(kind);
  40213. if (!vertexBuffer) {
  40214. return;
  40215. }
  40216. vertexBuffer.update(data);
  40217. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40218. var stride = vertexBuffer.getStrideSize();
  40219. this._totalVertices = data.length / stride;
  40220. this.updateBoundingInfo(updateExtends, data);
  40221. }
  40222. this.notifyUpdate(kind);
  40223. };
  40224. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  40225. if (updateExtends) {
  40226. this.updateExtend(data);
  40227. }
  40228. var meshes = this._meshes;
  40229. var numOfMeshes = meshes.length;
  40230. for (var index = 0; index < numOfMeshes; index++) {
  40231. var mesh = meshes[index];
  40232. mesh._resetPointsArrayCache();
  40233. if (updateExtends) {
  40234. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40235. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40236. var subMesh = mesh.subMeshes[subIndex];
  40237. subMesh.refreshBoundingInfo();
  40238. }
  40239. }
  40240. }
  40241. };
  40242. Geometry.prototype._bind = function (effect, indexToBind) {
  40243. if (indexToBind === void 0) { indexToBind = undefined; }
  40244. if (indexToBind === undefined) {
  40245. indexToBind = this._indexBuffer;
  40246. }
  40247. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40248. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  40249. return;
  40250. }
  40251. // Using VAO
  40252. if (!this._vertexArrayObjects[effect.key]) {
  40253. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  40254. }
  40255. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40256. };
  40257. Geometry.prototype.getTotalVertices = function () {
  40258. if (!this.isReady()) {
  40259. return 0;
  40260. }
  40261. return this._totalVertices;
  40262. };
  40263. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  40264. var vertexBuffer = this.getVertexBuffer(kind);
  40265. if (!vertexBuffer) {
  40266. return null;
  40267. }
  40268. var orig = vertexBuffer.getData();
  40269. if (!copyWhenShared || this._meshes.length === 1) {
  40270. return orig;
  40271. }
  40272. else {
  40273. var len = orig.length;
  40274. var copy = [];
  40275. for (var i = 0; i < len; i++) {
  40276. copy.push(orig[i]);
  40277. }
  40278. return copy;
  40279. }
  40280. };
  40281. Geometry.prototype.getVertexBuffer = function (kind) {
  40282. if (!this.isReady()) {
  40283. return null;
  40284. }
  40285. return this._vertexBuffers[kind];
  40286. };
  40287. Geometry.prototype.getVertexBuffers = function () {
  40288. if (!this.isReady()) {
  40289. return null;
  40290. }
  40291. return this._vertexBuffers;
  40292. };
  40293. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40294. if (!this._vertexBuffers) {
  40295. if (this._delayInfo) {
  40296. return this._delayInfo.indexOf(kind) !== -1;
  40297. }
  40298. return false;
  40299. }
  40300. return this._vertexBuffers[kind] !== undefined;
  40301. };
  40302. Geometry.prototype.getVerticesDataKinds = function () {
  40303. var result = [];
  40304. var kind;
  40305. if (!this._vertexBuffers && this._delayInfo) {
  40306. for (kind in this._delayInfo) {
  40307. result.push(kind);
  40308. }
  40309. }
  40310. else {
  40311. for (kind in this._vertexBuffers) {
  40312. result.push(kind);
  40313. }
  40314. }
  40315. return result;
  40316. };
  40317. Geometry.prototype.setIndices = function (indices, totalVertices) {
  40318. if (this._indexBuffer) {
  40319. this._engine._releaseBuffer(this._indexBuffer);
  40320. }
  40321. this._disposeVertexArrayObjects();
  40322. this._indices = indices;
  40323. if (this._meshes.length !== 0 && this._indices) {
  40324. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40325. }
  40326. if (totalVertices !== undefined) {
  40327. this._totalVertices = totalVertices;
  40328. }
  40329. var meshes = this._meshes;
  40330. var numOfMeshes = meshes.length;
  40331. for (var index = 0; index < numOfMeshes; index++) {
  40332. meshes[index]._createGlobalSubMesh();
  40333. }
  40334. this.notifyUpdate();
  40335. };
  40336. Geometry.prototype.getTotalIndices = function () {
  40337. if (!this.isReady()) {
  40338. return 0;
  40339. }
  40340. return this._indices.length;
  40341. };
  40342. Geometry.prototype.getIndices = function (copyWhenShared) {
  40343. if (!this.isReady()) {
  40344. return null;
  40345. }
  40346. var orig = this._indices;
  40347. if (!copyWhenShared || this._meshes.length === 1) {
  40348. return orig;
  40349. }
  40350. else {
  40351. var len = orig.length;
  40352. var copy = [];
  40353. for (var i = 0; i < len; i++) {
  40354. copy.push(orig[i]);
  40355. }
  40356. return copy;
  40357. }
  40358. };
  40359. Geometry.prototype.getIndexBuffer = function () {
  40360. if (!this.isReady()) {
  40361. return null;
  40362. }
  40363. return this._indexBuffer;
  40364. };
  40365. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40366. var meshes = this._meshes;
  40367. var index = meshes.indexOf(mesh);
  40368. if (index === -1) {
  40369. return;
  40370. }
  40371. meshes.splice(index, 1);
  40372. mesh._geometry = null;
  40373. if (meshes.length === 0 && shouldDispose) {
  40374. this.dispose();
  40375. }
  40376. };
  40377. Geometry.prototype.applyToMesh = function (mesh) {
  40378. if (mesh._geometry === this) {
  40379. return;
  40380. }
  40381. var previousGeometry = mesh._geometry;
  40382. if (previousGeometry) {
  40383. previousGeometry.releaseForMesh(mesh);
  40384. }
  40385. var meshes = this._meshes;
  40386. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40387. mesh._geometry = this;
  40388. this._scene.pushGeometry(this);
  40389. meshes.push(mesh);
  40390. if (this.isReady()) {
  40391. this._applyToMesh(mesh);
  40392. }
  40393. else {
  40394. mesh._boundingInfo = this._boundingInfo;
  40395. }
  40396. };
  40397. Geometry.prototype.updateExtend = function (data, stride) {
  40398. if (data === void 0) { data = null; }
  40399. if (!data) {
  40400. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  40401. }
  40402. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  40403. };
  40404. Geometry.prototype._applyToMesh = function (mesh) {
  40405. var numOfMeshes = this._meshes.length;
  40406. // vertexBuffers
  40407. for (var kind in this._vertexBuffers) {
  40408. if (numOfMeshes === 1) {
  40409. this._vertexBuffers[kind].create();
  40410. }
  40411. var buffer = this._vertexBuffers[kind].getBuffer();
  40412. if (buffer)
  40413. buffer.references = numOfMeshes;
  40414. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40415. mesh._resetPointsArrayCache();
  40416. if (!this._extend) {
  40417. this.updateExtend(this._vertexBuffers[kind].getData());
  40418. }
  40419. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40420. mesh._createGlobalSubMesh();
  40421. //bounding info was just created again, world matrix should be applied again.
  40422. mesh._updateBoundingInfo();
  40423. }
  40424. }
  40425. // indexBuffer
  40426. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40427. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40428. }
  40429. if (this._indexBuffer) {
  40430. this._indexBuffer.references = numOfMeshes;
  40431. }
  40432. };
  40433. Geometry.prototype.notifyUpdate = function (kind) {
  40434. if (this.onGeometryUpdated) {
  40435. this.onGeometryUpdated(this, kind);
  40436. }
  40437. };
  40438. Geometry.prototype.load = function (scene, onLoaded) {
  40439. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40440. return;
  40441. }
  40442. if (this.isReady()) {
  40443. if (onLoaded) {
  40444. onLoaded();
  40445. }
  40446. return;
  40447. }
  40448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40449. this._queueLoad(scene, onLoaded);
  40450. };
  40451. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40452. var _this = this;
  40453. scene._addPendingData(this);
  40454. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  40455. _this._delayLoadingFunction(JSON.parse(data), _this);
  40456. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40457. _this._delayInfo = [];
  40458. scene._removePendingData(_this);
  40459. var meshes = _this._meshes;
  40460. var numOfMeshes = meshes.length;
  40461. for (var index = 0; index < numOfMeshes; index++) {
  40462. _this._applyToMesh(meshes[index]);
  40463. }
  40464. if (onLoaded) {
  40465. onLoaded();
  40466. }
  40467. }, function () { }, scene.database);
  40468. };
  40469. /**
  40470. * Invert the geometry to move from a right handed system to a left handed one.
  40471. */
  40472. Geometry.prototype.toLeftHanded = function () {
  40473. // Flip faces
  40474. var tIndices = this.getIndices(false);
  40475. if (tIndices != null && tIndices.length > 0) {
  40476. for (var i = 0; i < tIndices.length; i += 3) {
  40477. var tTemp = tIndices[i + 0];
  40478. tIndices[i + 0] = tIndices[i + 2];
  40479. tIndices[i + 2] = tTemp;
  40480. }
  40481. this.setIndices(tIndices);
  40482. }
  40483. // Negate position.z
  40484. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40485. if (tPositions != null && tPositions.length > 0) {
  40486. for (var i = 0; i < tPositions.length; i += 3) {
  40487. tPositions[i + 2] = -tPositions[i + 2];
  40488. }
  40489. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40490. }
  40491. // Negate normal.z
  40492. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40493. if (tNormals != null && tNormals.length > 0) {
  40494. for (var i = 0; i < tNormals.length; i += 3) {
  40495. tNormals[i + 2] = -tNormals[i + 2];
  40496. }
  40497. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40498. }
  40499. };
  40500. Geometry.prototype.isDisposed = function () {
  40501. return this._isDisposed;
  40502. };
  40503. Geometry.prototype._disposeVertexArrayObjects = function () {
  40504. if (this._vertexArrayObjects) {
  40505. for (var kind in this._vertexArrayObjects) {
  40506. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40507. }
  40508. this._vertexArrayObjects = {};
  40509. }
  40510. };
  40511. Geometry.prototype.dispose = function () {
  40512. var meshes = this._meshes;
  40513. var numOfMeshes = meshes.length;
  40514. var index;
  40515. for (index = 0; index < numOfMeshes; index++) {
  40516. this.releaseForMesh(meshes[index]);
  40517. }
  40518. this._meshes = [];
  40519. this._disposeVertexArrayObjects();
  40520. for (var kind in this._vertexBuffers) {
  40521. this._vertexBuffers[kind].dispose();
  40522. }
  40523. this._vertexBuffers = {};
  40524. this._totalVertices = 0;
  40525. if (this._indexBuffer) {
  40526. this._engine._releaseBuffer(this._indexBuffer);
  40527. }
  40528. this._indexBuffer = null;
  40529. this._indices = [];
  40530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40531. this.delayLoadingFile = null;
  40532. this._delayLoadingFunction = null;
  40533. this._delayInfo = [];
  40534. this._boundingInfo = null;
  40535. this._scene.removeGeometry(this);
  40536. this._isDisposed = true;
  40537. };
  40538. Geometry.prototype.copy = function (id) {
  40539. var vertexData = new BABYLON.VertexData();
  40540. vertexData.indices = [];
  40541. var indices = this.getIndices();
  40542. for (var index = 0; index < indices.length; index++) {
  40543. vertexData.indices.push(indices[index]);
  40544. }
  40545. var updatable = false;
  40546. var stopChecking = false;
  40547. var kind;
  40548. for (kind in this._vertexBuffers) {
  40549. // using slice() to make a copy of the array and not just reference it
  40550. var data = this.getVerticesData(kind);
  40551. if (data instanceof Float32Array) {
  40552. vertexData.set(new Float32Array(data), kind);
  40553. }
  40554. else {
  40555. vertexData.set(data.slice(0), kind);
  40556. }
  40557. if (!stopChecking) {
  40558. updatable = this.getVertexBuffer(kind).isUpdatable();
  40559. stopChecking = !updatable;
  40560. }
  40561. }
  40562. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  40563. geometry.delayLoadState = this.delayLoadState;
  40564. geometry.delayLoadingFile = this.delayLoadingFile;
  40565. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40566. for (kind in this._delayInfo) {
  40567. geometry._delayInfo = geometry._delayInfo || [];
  40568. geometry._delayInfo.push(kind);
  40569. }
  40570. // Bounding info
  40571. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40572. return geometry;
  40573. };
  40574. Geometry.prototype.serialize = function () {
  40575. var serializationObject = {};
  40576. serializationObject.id = this.id;
  40577. if (BABYLON.Tags.HasTags(this)) {
  40578. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40579. }
  40580. return serializationObject;
  40581. };
  40582. Geometry.prototype.serializeVerticeData = function () {
  40583. var serializationObject = this.serialize();
  40584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40585. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40586. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  40587. serializationObject.positions._updatable = true;
  40588. }
  40589. }
  40590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40591. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40592. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  40593. serializationObject.normals._updatable = true;
  40594. }
  40595. }
  40596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40597. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40598. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  40599. serializationObject.uvs._updatable = true;
  40600. }
  40601. }
  40602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40603. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  40604. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  40605. serializationObject.uv2s._updatable = true;
  40606. }
  40607. }
  40608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40609. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  40610. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  40611. serializationObject.uv3s._updatable = true;
  40612. }
  40613. }
  40614. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40615. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  40616. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  40617. serializationObject.uv4s._updatable = true;
  40618. }
  40619. }
  40620. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40621. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  40622. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  40623. serializationObject.uv5s._updatable = true;
  40624. }
  40625. }
  40626. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40627. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  40628. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  40629. serializationObject.uv6s._updatable = true;
  40630. }
  40631. }
  40632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40633. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40634. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  40635. serializationObject.colors._updatable = true;
  40636. }
  40637. }
  40638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40639. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40640. serializationObject.matricesIndices._isExpanded = true;
  40641. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  40642. serializationObject.matricesIndices._updatable = true;
  40643. }
  40644. }
  40645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40646. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  40647. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  40648. serializationObject.matricesWeights._updatable = true;
  40649. }
  40650. }
  40651. serializationObject.indices = this.getIndices();
  40652. return serializationObject;
  40653. };
  40654. // Statics
  40655. Geometry.ExtractFromMesh = function (mesh, id) {
  40656. var geometry = mesh._geometry;
  40657. if (!geometry) {
  40658. return null;
  40659. }
  40660. return geometry.copy(id);
  40661. };
  40662. /**
  40663. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40664. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40665. * Be aware Math.random() could cause collisions, but:
  40666. * "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"
  40667. */
  40668. Geometry.RandomId = function () {
  40669. return BABYLON.Tools.RandomId();
  40670. };
  40671. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  40672. var scene = mesh.getScene();
  40673. // Geometry
  40674. var geometryId = parsedGeometry.geometryId;
  40675. if (geometryId) {
  40676. var geometry = scene.getGeometryByID(geometryId);
  40677. if (geometry) {
  40678. geometry.applyToMesh(mesh);
  40679. }
  40680. }
  40681. else if (parsedGeometry instanceof ArrayBuffer) {
  40682. var binaryInfo = mesh._binaryInfo;
  40683. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40684. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40685. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40686. }
  40687. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40688. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40689. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40690. }
  40691. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40692. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40693. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40694. }
  40695. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40696. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40697. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40698. }
  40699. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40700. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40701. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40702. }
  40703. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40704. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40705. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40706. }
  40707. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40708. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40709. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40710. }
  40711. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40712. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40713. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40714. }
  40715. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40716. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40717. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40718. }
  40719. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40720. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40722. }
  40723. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40724. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40726. }
  40727. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40728. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40729. mesh.setIndices(indicesData);
  40730. }
  40731. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40732. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40733. mesh.subMeshes = [];
  40734. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40735. var materialIndex = subMeshesData[(i * 5) + 0];
  40736. var verticesStart = subMeshesData[(i * 5) + 1];
  40737. var verticesCount = subMeshesData[(i * 5) + 2];
  40738. var indexStart = subMeshesData[(i * 5) + 3];
  40739. var indexCount = subMeshesData[(i * 5) + 4];
  40740. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40741. }
  40742. }
  40743. }
  40744. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40745. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40746. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40747. if (parsedGeometry.uvs) {
  40748. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40749. }
  40750. if (parsedGeometry.uvs2) {
  40751. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40752. }
  40753. if (parsedGeometry.uvs3) {
  40754. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40755. }
  40756. if (parsedGeometry.uvs4) {
  40757. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40758. }
  40759. if (parsedGeometry.uvs5) {
  40760. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40761. }
  40762. if (parsedGeometry.uvs6) {
  40763. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40764. }
  40765. if (parsedGeometry.colors) {
  40766. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40767. }
  40768. if (parsedGeometry.matricesIndices) {
  40769. if (!parsedGeometry.matricesIndices._isExpanded) {
  40770. var floatIndices = [];
  40771. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40772. var matricesIndex = parsedGeometry.matricesIndices[i];
  40773. floatIndices.push(matricesIndex & 0x000000FF);
  40774. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40775. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40776. floatIndices.push(matricesIndex >> 24);
  40777. }
  40778. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40779. }
  40780. else {
  40781. delete parsedGeometry.matricesIndices._isExpanded;
  40782. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40783. }
  40784. }
  40785. if (parsedGeometry.matricesIndicesExtra) {
  40786. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40787. var floatIndices = [];
  40788. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40789. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40790. floatIndices.push(matricesIndex & 0x000000FF);
  40791. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40792. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40793. floatIndices.push(matricesIndex >> 24);
  40794. }
  40795. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40796. }
  40797. else {
  40798. delete parsedGeometry.matricesIndices._isExpanded;
  40799. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40800. }
  40801. }
  40802. if (parsedGeometry.matricesWeights) {
  40803. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40804. }
  40805. if (parsedGeometry.matricesWeightsExtra) {
  40806. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40807. }
  40808. mesh.setIndices(parsedGeometry.indices);
  40809. }
  40810. // SubMeshes
  40811. if (parsedGeometry.subMeshes) {
  40812. mesh.subMeshes = [];
  40813. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40814. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40815. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40816. }
  40817. }
  40818. // Flat shading
  40819. if (mesh._shouldGenerateFlatShading) {
  40820. mesh.convertToFlatShadedMesh();
  40821. delete mesh._shouldGenerateFlatShading;
  40822. }
  40823. // Update
  40824. mesh.computeWorldMatrix(true);
  40825. // Octree
  40826. if (scene['_selectionOctree']) {
  40827. scene['_selectionOctree'].addMesh(mesh);
  40828. }
  40829. };
  40830. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40831. if (scene.getGeometryByID(parsedVertexData.id)) {
  40832. return null; // null since geometry could be something else than a box...
  40833. }
  40834. var geometry = new Geometry(parsedVertexData.id, scene);
  40835. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40836. if (parsedVertexData.delayLoadingFile) {
  40837. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40838. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40839. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40840. geometry._delayInfo = [];
  40841. if (parsedVertexData.hasUVs) {
  40842. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40843. }
  40844. if (parsedVertexData.hasUVs2) {
  40845. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40846. }
  40847. if (parsedVertexData.hasUVs3) {
  40848. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40849. }
  40850. if (parsedVertexData.hasUVs4) {
  40851. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40852. }
  40853. if (parsedVertexData.hasUVs5) {
  40854. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40855. }
  40856. if (parsedVertexData.hasUVs6) {
  40857. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40858. }
  40859. if (parsedVertexData.hasColors) {
  40860. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40861. }
  40862. if (parsedVertexData.hasMatricesIndices) {
  40863. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40864. }
  40865. if (parsedVertexData.hasMatricesWeights) {
  40866. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40867. }
  40868. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40869. }
  40870. else {
  40871. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40872. }
  40873. scene.pushGeometry(geometry, true);
  40874. return geometry;
  40875. };
  40876. return Geometry;
  40877. }());
  40878. BABYLON.Geometry = Geometry;
  40879. /////// Primitives //////////////////////////////////////////////
  40880. (function (Geometry) {
  40881. var Primitives;
  40882. (function (Primitives) {
  40883. /// Abstract class
  40884. var _Primitive = (function (_super) {
  40885. __extends(_Primitive, _super);
  40886. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  40887. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  40888. _this._canBeRegenerated = _canBeRegenerated;
  40889. _this._beingRegenerated = true;
  40890. _this.regenerate();
  40891. _this._beingRegenerated = false;
  40892. return _this;
  40893. }
  40894. _Primitive.prototype.canBeRegenerated = function () {
  40895. return this._canBeRegenerated;
  40896. };
  40897. _Primitive.prototype.regenerate = function () {
  40898. if (!this._canBeRegenerated) {
  40899. return;
  40900. }
  40901. this._beingRegenerated = true;
  40902. this.setAllVerticesData(this._regenerateVertexData(), false);
  40903. this._beingRegenerated = false;
  40904. };
  40905. _Primitive.prototype.asNewGeometry = function (id) {
  40906. return _super.prototype.copy.call(this, id);
  40907. };
  40908. // overrides
  40909. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  40910. if (!this._beingRegenerated) {
  40911. return;
  40912. }
  40913. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40914. };
  40915. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  40916. if (!this._beingRegenerated) {
  40917. return;
  40918. }
  40919. _super.prototype.setVerticesData.call(this, kind, data, false);
  40920. };
  40921. // to override
  40922. // protected
  40923. _Primitive.prototype._regenerateVertexData = function () {
  40924. throw new Error("Abstract method");
  40925. };
  40926. _Primitive.prototype.copy = function (id) {
  40927. throw new Error("Must be overriden in sub-classes.");
  40928. };
  40929. _Primitive.prototype.serialize = function () {
  40930. var serializationObject = _super.prototype.serialize.call(this);
  40931. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40932. return serializationObject;
  40933. };
  40934. return _Primitive;
  40935. }(Geometry));
  40936. Primitives._Primitive = _Primitive;
  40937. var Ribbon = (function (_super) {
  40938. __extends(Ribbon, _super);
  40939. // Members
  40940. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  40941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40942. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40943. _this.pathArray = pathArray;
  40944. _this.closeArray = closeArray;
  40945. _this.closePath = closePath;
  40946. _this.offset = offset;
  40947. _this.side = side;
  40948. return _this;
  40949. }
  40950. Ribbon.prototype._regenerateVertexData = function () {
  40951. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40952. };
  40953. Ribbon.prototype.copy = function (id) {
  40954. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  40955. };
  40956. return Ribbon;
  40957. }(_Primitive));
  40958. Primitives.Ribbon = Ribbon;
  40959. var Box = (function (_super) {
  40960. __extends(Box, _super);
  40961. // Members
  40962. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  40963. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40964. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40965. _this.size = size;
  40966. _this.side = side;
  40967. return _this;
  40968. }
  40969. Box.prototype._regenerateVertexData = function () {
  40970. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40971. };
  40972. Box.prototype.copy = function (id) {
  40973. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40974. };
  40975. Box.prototype.serialize = function () {
  40976. var serializationObject = _super.prototype.serialize.call(this);
  40977. serializationObject.size = this.size;
  40978. return serializationObject;
  40979. };
  40980. Box.Parse = function (parsedBox, scene) {
  40981. if (scene.getGeometryByID(parsedBox.id)) {
  40982. return null; // null since geometry could be something else than a box...
  40983. }
  40984. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40985. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40986. scene.pushGeometry(box, true);
  40987. return box;
  40988. };
  40989. return Box;
  40990. }(_Primitive));
  40991. Primitives.Box = Box;
  40992. var Sphere = (function (_super) {
  40993. __extends(Sphere, _super);
  40994. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  40995. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40996. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40997. _this.segments = segments;
  40998. _this.diameter = diameter;
  40999. _this.side = side;
  41000. return _this;
  41001. }
  41002. Sphere.prototype._regenerateVertexData = function () {
  41003. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41004. };
  41005. Sphere.prototype.copy = function (id) {
  41006. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41007. };
  41008. Sphere.prototype.serialize = function () {
  41009. var serializationObject = _super.prototype.serialize.call(this);
  41010. serializationObject.segments = this.segments;
  41011. serializationObject.diameter = this.diameter;
  41012. return serializationObject;
  41013. };
  41014. Sphere.Parse = function (parsedSphere, scene) {
  41015. if (scene.getGeometryByID(parsedSphere.id)) {
  41016. return null; // null since geometry could be something else than a sphere...
  41017. }
  41018. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41019. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41020. scene.pushGeometry(sphere, true);
  41021. return sphere;
  41022. };
  41023. return Sphere;
  41024. }(_Primitive));
  41025. Primitives.Sphere = Sphere;
  41026. var Disc = (function (_super) {
  41027. __extends(Disc, _super);
  41028. // Members
  41029. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  41030. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41031. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41032. _this.radius = radius;
  41033. _this.tessellation = tessellation;
  41034. _this.side = side;
  41035. return _this;
  41036. }
  41037. Disc.prototype._regenerateVertexData = function () {
  41038. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41039. };
  41040. Disc.prototype.copy = function (id) {
  41041. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41042. };
  41043. return Disc;
  41044. }(_Primitive));
  41045. Primitives.Disc = Disc;
  41046. var Cylinder = (function (_super) {
  41047. __extends(Cylinder, _super);
  41048. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  41049. if (subdivisions === void 0) { subdivisions = 1; }
  41050. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41051. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41052. _this.height = height;
  41053. _this.diameterTop = diameterTop;
  41054. _this.diameterBottom = diameterBottom;
  41055. _this.tessellation = tessellation;
  41056. _this.subdivisions = subdivisions;
  41057. _this.side = side;
  41058. return _this;
  41059. }
  41060. Cylinder.prototype._regenerateVertexData = function () {
  41061. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41062. };
  41063. Cylinder.prototype.copy = function (id) {
  41064. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41065. };
  41066. Cylinder.prototype.serialize = function () {
  41067. var serializationObject = _super.prototype.serialize.call(this);
  41068. serializationObject.height = this.height;
  41069. serializationObject.diameterTop = this.diameterTop;
  41070. serializationObject.diameterBottom = this.diameterBottom;
  41071. serializationObject.tessellation = this.tessellation;
  41072. return serializationObject;
  41073. };
  41074. Cylinder.Parse = function (parsedCylinder, scene) {
  41075. if (scene.getGeometryByID(parsedCylinder.id)) {
  41076. return null; // null since geometry could be something else than a cylinder...
  41077. }
  41078. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41079. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41080. scene.pushGeometry(cylinder, true);
  41081. return cylinder;
  41082. };
  41083. return Cylinder;
  41084. }(_Primitive));
  41085. Primitives.Cylinder = Cylinder;
  41086. var Torus = (function (_super) {
  41087. __extends(Torus, _super);
  41088. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  41089. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41090. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41091. _this.diameter = diameter;
  41092. _this.thickness = thickness;
  41093. _this.tessellation = tessellation;
  41094. _this.side = side;
  41095. return _this;
  41096. }
  41097. Torus.prototype._regenerateVertexData = function () {
  41098. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41099. };
  41100. Torus.prototype.copy = function (id) {
  41101. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41102. };
  41103. Torus.prototype.serialize = function () {
  41104. var serializationObject = _super.prototype.serialize.call(this);
  41105. serializationObject.diameter = this.diameter;
  41106. serializationObject.thickness = this.thickness;
  41107. serializationObject.tessellation = this.tessellation;
  41108. return serializationObject;
  41109. };
  41110. Torus.Parse = function (parsedTorus, scene) {
  41111. if (scene.getGeometryByID(parsedTorus.id)) {
  41112. return null; // null since geometry could be something else than a torus...
  41113. }
  41114. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41115. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41116. scene.pushGeometry(torus, true);
  41117. return torus;
  41118. };
  41119. return Torus;
  41120. }(_Primitive));
  41121. Primitives.Torus = Torus;
  41122. var Ground = (function (_super) {
  41123. __extends(Ground, _super);
  41124. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  41125. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41126. _this.width = width;
  41127. _this.height = height;
  41128. _this.subdivisions = subdivisions;
  41129. return _this;
  41130. }
  41131. Ground.prototype._regenerateVertexData = function () {
  41132. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41133. };
  41134. Ground.prototype.copy = function (id) {
  41135. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41136. };
  41137. Ground.prototype.serialize = function () {
  41138. var serializationObject = _super.prototype.serialize.call(this);
  41139. serializationObject.width = this.width;
  41140. serializationObject.height = this.height;
  41141. serializationObject.subdivisions = this.subdivisions;
  41142. return serializationObject;
  41143. };
  41144. Ground.Parse = function (parsedGround, scene) {
  41145. if (scene.getGeometryByID(parsedGround.id)) {
  41146. return null; // null since geometry could be something else than a ground...
  41147. }
  41148. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41149. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41150. scene.pushGeometry(ground, true);
  41151. return ground;
  41152. };
  41153. return Ground;
  41154. }(_Primitive));
  41155. Primitives.Ground = Ground;
  41156. var TiledGround = (function (_super) {
  41157. __extends(TiledGround, _super);
  41158. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  41159. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41160. _this.xmin = xmin;
  41161. _this.zmin = zmin;
  41162. _this.xmax = xmax;
  41163. _this.zmax = zmax;
  41164. _this.subdivisions = subdivisions;
  41165. _this.precision = precision;
  41166. return _this;
  41167. }
  41168. TiledGround.prototype._regenerateVertexData = function () {
  41169. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41170. };
  41171. TiledGround.prototype.copy = function (id) {
  41172. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41173. };
  41174. return TiledGround;
  41175. }(_Primitive));
  41176. Primitives.TiledGround = TiledGround;
  41177. var Plane = (function (_super) {
  41178. __extends(Plane, _super);
  41179. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  41180. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41181. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41182. _this.size = size;
  41183. _this.side = side;
  41184. return _this;
  41185. }
  41186. Plane.prototype._regenerateVertexData = function () {
  41187. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41188. };
  41189. Plane.prototype.copy = function (id) {
  41190. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41191. };
  41192. Plane.prototype.serialize = function () {
  41193. var serializationObject = _super.prototype.serialize.call(this);
  41194. serializationObject.size = this.size;
  41195. return serializationObject;
  41196. };
  41197. Plane.Parse = function (parsedPlane, scene) {
  41198. if (scene.getGeometryByID(parsedPlane.id)) {
  41199. return null; // null since geometry could be something else than a ground...
  41200. }
  41201. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41202. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41203. scene.pushGeometry(plane, true);
  41204. return plane;
  41205. };
  41206. return Plane;
  41207. }(_Primitive));
  41208. Primitives.Plane = Plane;
  41209. var TorusKnot = (function (_super) {
  41210. __extends(TorusKnot, _super);
  41211. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  41212. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41213. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41214. _this.radius = radius;
  41215. _this.tube = tube;
  41216. _this.radialSegments = radialSegments;
  41217. _this.tubularSegments = tubularSegments;
  41218. _this.p = p;
  41219. _this.q = q;
  41220. _this.side = side;
  41221. return _this;
  41222. }
  41223. TorusKnot.prototype._regenerateVertexData = function () {
  41224. 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 });
  41225. };
  41226. TorusKnot.prototype.copy = function (id) {
  41227. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41228. };
  41229. TorusKnot.prototype.serialize = function () {
  41230. var serializationObject = _super.prototype.serialize.call(this);
  41231. serializationObject.radius = this.radius;
  41232. serializationObject.tube = this.tube;
  41233. serializationObject.radialSegments = this.radialSegments;
  41234. serializationObject.tubularSegments = this.tubularSegments;
  41235. serializationObject.p = this.p;
  41236. serializationObject.q = this.q;
  41237. return serializationObject;
  41238. };
  41239. ;
  41240. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  41241. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41242. return null; // null since geometry could be something else than a ground...
  41243. }
  41244. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41245. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41246. scene.pushGeometry(torusKnot, true);
  41247. return torusKnot;
  41248. };
  41249. return TorusKnot;
  41250. }(_Primitive));
  41251. Primitives.TorusKnot = TorusKnot;
  41252. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  41253. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  41254. })(BABYLON || (BABYLON = {}));
  41255. //# sourceMappingURL=babylon.geometry.js.map
  41256. /// <reference path="babylon.mesh.ts" />
  41257. var BABYLON;
  41258. (function (BABYLON) {
  41259. var GroundMesh = (function (_super) {
  41260. __extends(GroundMesh, _super);
  41261. function GroundMesh(name, scene) {
  41262. var _this = _super.call(this, name, scene) || this;
  41263. _this.generateOctree = false;
  41264. _this._worldInverse = new BABYLON.Matrix();
  41265. return _this;
  41266. }
  41267. GroundMesh.prototype.getClassName = function () {
  41268. return "GroundMesh";
  41269. };
  41270. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41271. get: function () {
  41272. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41273. },
  41274. enumerable: true,
  41275. configurable: true
  41276. });
  41277. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41278. get: function () {
  41279. return this._subdivisionsX;
  41280. },
  41281. enumerable: true,
  41282. configurable: true
  41283. });
  41284. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41285. get: function () {
  41286. return this._subdivisionsY;
  41287. },
  41288. enumerable: true,
  41289. configurable: true
  41290. });
  41291. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41292. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41293. this._subdivisionsX = chunksCount;
  41294. this._subdivisionsY = chunksCount;
  41295. this.subdivide(chunksCount);
  41296. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41297. };
  41298. /**
  41299. * Returns a height (y) value in the Worl system :
  41300. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41301. * Returns the ground y position if (x, z) are outside the ground surface.
  41302. */
  41303. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41304. var world = this.getWorldMatrix();
  41305. var invMat = BABYLON.Tmp.Matrix[5];
  41306. world.invertToRef(invMat);
  41307. var tmpVect = BABYLON.Tmp.Vector3[8];
  41308. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41309. x = tmpVect.x;
  41310. z = tmpVect.z;
  41311. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41312. return this.position.y;
  41313. }
  41314. if (!this._heightQuads || this._heightQuads.length == 0) {
  41315. this._initHeightQuads();
  41316. this._computeHeightQuads();
  41317. }
  41318. var facet = this._getFacetAt(x, z);
  41319. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41320. // return y in the World system
  41321. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41322. return tmpVect.y;
  41323. };
  41324. /**
  41325. * Returns a normalized vector (Vector3) orthogonal to the ground
  41326. * at the ground coordinates (x, z) expressed in the World system.
  41327. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41328. */
  41329. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41330. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41331. this.getNormalAtCoordinatesToRef(x, z, normal);
  41332. return normal;
  41333. };
  41334. /**
  41335. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41336. * at the ground coordinates (x, z) expressed in the World system.
  41337. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41338. * Returns the GroundMesh.
  41339. */
  41340. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41341. var world = this.getWorldMatrix();
  41342. var tmpMat = BABYLON.Tmp.Matrix[5];
  41343. world.invertToRef(tmpMat);
  41344. var tmpVect = BABYLON.Tmp.Vector3[8];
  41345. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41346. x = tmpVect.x;
  41347. z = tmpVect.z;
  41348. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41349. return this;
  41350. }
  41351. if (!this._heightQuads || this._heightQuads.length == 0) {
  41352. this._initHeightQuads();
  41353. this._computeHeightQuads();
  41354. }
  41355. var facet = this._getFacetAt(x, z);
  41356. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41357. return this;
  41358. };
  41359. /**
  41360. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41361. * if the ground has been updated.
  41362. * This can be used in the render loop.
  41363. * Returns the GroundMesh.
  41364. */
  41365. GroundMesh.prototype.updateCoordinateHeights = function () {
  41366. if (!this._heightQuads || this._heightQuads.length == 0) {
  41367. this._initHeightQuads();
  41368. }
  41369. this._computeHeightQuads();
  41370. return this;
  41371. };
  41372. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41373. GroundMesh.prototype._getFacetAt = function (x, z) {
  41374. // retrieve col and row from x, z coordinates in the ground local system
  41375. var subdivisionsX = this._subdivisionsX;
  41376. var subdivisionsY = this._subdivisionsY;
  41377. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41378. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41379. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41380. var facet;
  41381. if (z < quad.slope.x * x + quad.slope.y) {
  41382. facet = quad.facet1;
  41383. }
  41384. else {
  41385. facet = quad.facet2;
  41386. }
  41387. return facet;
  41388. };
  41389. // Creates and populates the heightMap array with "facet" elements :
  41390. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41391. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41392. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41393. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41394. // Returns the GroundMesh.
  41395. GroundMesh.prototype._initHeightQuads = function () {
  41396. var subdivisionsX = this._subdivisionsX;
  41397. var subdivisionsY = this._subdivisionsY;
  41398. this._heightQuads = new Array();
  41399. for (var row = 0; row < subdivisionsY; row++) {
  41400. for (var col = 0; col < subdivisionsX; col++) {
  41401. 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) };
  41402. this._heightQuads[row * subdivisionsX + col] = quad;
  41403. }
  41404. }
  41405. return this;
  41406. };
  41407. // Compute each quad element values and update the the heightMap array :
  41408. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41409. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41410. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41411. // Returns the GroundMesh.
  41412. GroundMesh.prototype._computeHeightQuads = function () {
  41413. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41414. var v1 = BABYLON.Tmp.Vector3[3];
  41415. var v2 = BABYLON.Tmp.Vector3[2];
  41416. var v3 = BABYLON.Tmp.Vector3[1];
  41417. var v4 = BABYLON.Tmp.Vector3[0];
  41418. var v1v2 = BABYLON.Tmp.Vector3[4];
  41419. var v1v3 = BABYLON.Tmp.Vector3[5];
  41420. var v1v4 = BABYLON.Tmp.Vector3[6];
  41421. var norm1 = BABYLON.Tmp.Vector3[7];
  41422. var norm2 = BABYLON.Tmp.Vector3[8];
  41423. var i = 0;
  41424. var j = 0;
  41425. var k = 0;
  41426. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41427. var h = 0;
  41428. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41429. var d2 = 0;
  41430. var subdivisionsX = this._subdivisionsX;
  41431. var subdivisionsY = this._subdivisionsY;
  41432. for (var row = 0; row < subdivisionsY; row++) {
  41433. for (var col = 0; col < subdivisionsX; col++) {
  41434. i = col * 3;
  41435. j = row * (subdivisionsX + 1) * 3;
  41436. k = (row + 1) * (subdivisionsX + 1) * 3;
  41437. v1.x = positions[j + i];
  41438. v1.y = positions[j + i + 1];
  41439. v1.z = positions[j + i + 2];
  41440. v2.x = positions[j + i + 3];
  41441. v2.y = positions[j + i + 4];
  41442. v2.z = positions[j + i + 5];
  41443. v3.x = positions[k + i];
  41444. v3.y = positions[k + i + 1];
  41445. v3.z = positions[k + i + 2];
  41446. v4.x = positions[k + i + 3];
  41447. v4.y = positions[k + i + 4];
  41448. v4.z = positions[k + i + 5];
  41449. // 2D slope V1V4
  41450. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41451. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41452. // facet equations :
  41453. // we compute each facet normal vector
  41454. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41455. // we compute the value d by applying the equation to v1 which belongs to the plane
  41456. // then we store the facet equation in a Vector4
  41457. v2.subtractToRef(v1, v1v2);
  41458. v3.subtractToRef(v1, v1v3);
  41459. v4.subtractToRef(v1, v1v4);
  41460. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41461. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41462. norm1.normalize();
  41463. norm2.normalize();
  41464. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41465. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41466. var quad = this._heightQuads[row * subdivisionsX + col];
  41467. quad.slope.copyFromFloats(cd, h);
  41468. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41469. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41470. }
  41471. }
  41472. return this;
  41473. };
  41474. GroundMesh.prototype.serialize = function (serializationObject) {
  41475. _super.prototype.serialize.call(this, serializationObject);
  41476. serializationObject.subdivisionsX = this._subdivisionsX;
  41477. serializationObject.subdivisionsY = this._subdivisionsY;
  41478. serializationObject.minX = this._minX;
  41479. serializationObject.maxX = this._maxX;
  41480. serializationObject.minZ = this._minZ;
  41481. serializationObject.maxZ = this._maxZ;
  41482. serializationObject.width = this._width;
  41483. serializationObject.height = this._height;
  41484. };
  41485. GroundMesh.Parse = function (parsedMesh, scene) {
  41486. var result = new GroundMesh(parsedMesh.name, scene);
  41487. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41488. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41489. result._minX = parsedMesh.minX;
  41490. result._maxX = parsedMesh.maxX;
  41491. result._minZ = parsedMesh.minZ;
  41492. result._maxZ = parsedMesh.maxZ;
  41493. result._width = parsedMesh.width;
  41494. result._height = parsedMesh.height;
  41495. return result;
  41496. };
  41497. return GroundMesh;
  41498. }(BABYLON.Mesh));
  41499. BABYLON.GroundMesh = GroundMesh;
  41500. })(BABYLON || (BABYLON = {}));
  41501. //# sourceMappingURL=babylon.groundMesh.js.map
  41502. /// <reference path="babylon.mesh.ts" />
  41503. var BABYLON;
  41504. (function (BABYLON) {
  41505. var LinesMesh = (function (_super) {
  41506. __extends(LinesMesh, _super);
  41507. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  41508. if (parent === void 0) { parent = null; }
  41509. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41510. _this.color = new BABYLON.Color3(1, 1, 1);
  41511. _this.alpha = 1;
  41512. _this._positionBuffer = {};
  41513. if (source) {
  41514. _this.color = source.color.clone();
  41515. _this.alpha = source.alpha;
  41516. }
  41517. _this._intersectionThreshold = 0.1;
  41518. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  41519. attributes: [BABYLON.VertexBuffer.PositionKind],
  41520. uniforms: ["worldViewProjection", "color"],
  41521. needAlphaBlending: true
  41522. });
  41523. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  41524. return _this;
  41525. }
  41526. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41527. /**
  41528. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41529. * This margin is expressed in world space coordinates, so its value may vary.
  41530. * Default value is 0.1
  41531. * @returns the intersection Threshold value.
  41532. */
  41533. get: function () {
  41534. return this._intersectionThreshold;
  41535. },
  41536. /**
  41537. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41538. * This margin is expressed in world space coordinates, so its value may vary.
  41539. * @param value the new threshold to apply
  41540. */
  41541. set: function (value) {
  41542. if (this._intersectionThreshold === value) {
  41543. return;
  41544. }
  41545. this._intersectionThreshold = value;
  41546. if (this.geometry) {
  41547. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41548. }
  41549. },
  41550. enumerable: true,
  41551. configurable: true
  41552. });
  41553. /**
  41554. * Returns the string "LineMesh"
  41555. */
  41556. LinesMesh.prototype.getClassName = function () {
  41557. return "LinesMesh";
  41558. };
  41559. Object.defineProperty(LinesMesh.prototype, "material", {
  41560. get: function () {
  41561. return this._colorShader;
  41562. },
  41563. enumerable: true,
  41564. configurable: true
  41565. });
  41566. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41567. get: function () {
  41568. return false;
  41569. },
  41570. enumerable: true,
  41571. configurable: true
  41572. });
  41573. LinesMesh.prototype.createInstance = function (name) {
  41574. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41575. return null;
  41576. };
  41577. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41578. var engine = this.getScene().getEngine();
  41579. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  41580. // VBOs
  41581. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  41582. // Color
  41583. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41584. return this;
  41585. };
  41586. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41587. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41588. return this;
  41589. }
  41590. var engine = this.getScene().getEngine();
  41591. // Draw order
  41592. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41593. return this;
  41594. };
  41595. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41596. this._colorShader.dispose();
  41597. _super.prototype.dispose.call(this, doNotRecurse);
  41598. };
  41599. /**
  41600. * Returns a new LineMesh object cloned from the current one.
  41601. */
  41602. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41603. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41604. };
  41605. return LinesMesh;
  41606. }(BABYLON.Mesh));
  41607. BABYLON.LinesMesh = LinesMesh;
  41608. })(BABYLON || (BABYLON = {}));
  41609. //# sourceMappingURL=babylon.linesMesh.js.map
  41610. var BABYLON;
  41611. (function (BABYLON) {
  41612. var DefaultLoadingScreen = (function () {
  41613. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  41614. if (_loadingText === void 0) { _loadingText = ""; }
  41615. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  41616. var _this = this;
  41617. this._renderingCanvas = _renderingCanvas;
  41618. this._loadingText = _loadingText;
  41619. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  41620. // Resize
  41621. this._resizeLoadingUI = function () {
  41622. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  41623. _this._loadingDiv.style.position = "absolute";
  41624. _this._loadingDiv.style.left = canvasRect.left + "px";
  41625. _this._loadingDiv.style.top = canvasRect.top + "px";
  41626. _this._loadingDiv.style.width = canvasRect.width + "px";
  41627. _this._loadingDiv.style.height = canvasRect.height + "px";
  41628. };
  41629. }
  41630. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  41631. var _this = this;
  41632. if (this._loadingDiv) {
  41633. // Do not add a loading screen if there is already one
  41634. return;
  41635. }
  41636. this._loadingDiv = document.createElement("div");
  41637. this._loadingDiv.id = "babylonjsLoadingDiv";
  41638. this._loadingDiv.style.opacity = "0";
  41639. this._loadingDiv.style.transition = "opacity 1.5s ease";
  41640. // Loading text
  41641. this._loadingTextDiv = document.createElement("div");
  41642. this._loadingTextDiv.style.position = "absolute";
  41643. this._loadingTextDiv.style.left = "0";
  41644. this._loadingTextDiv.style.top = "50%";
  41645. this._loadingTextDiv.style.marginTop = "80px";
  41646. this._loadingTextDiv.style.width = "100%";
  41647. this._loadingTextDiv.style.height = "20px";
  41648. this._loadingTextDiv.style.fontFamily = "Arial";
  41649. this._loadingTextDiv.style.fontSize = "14px";
  41650. this._loadingTextDiv.style.color = "white";
  41651. this._loadingTextDiv.style.textAlign = "center";
  41652. this._loadingTextDiv.innerHTML = "Loading";
  41653. this._loadingDiv.appendChild(this._loadingTextDiv);
  41654. //set the predefined text
  41655. this._loadingTextDiv.innerHTML = this._loadingText;
  41656. // Loading img
  41657. var imgBack = new Image();
  41658. 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==";
  41659. imgBack.style.position = "absolute";
  41660. imgBack.style.left = "50%";
  41661. imgBack.style.top = "50%";
  41662. imgBack.style.marginLeft = "-50px";
  41663. imgBack.style.marginTop = "-50px";
  41664. imgBack.style.transition = "transform 1.0s ease";
  41665. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  41666. var deg = 360;
  41667. var onTransitionEnd = function () {
  41668. deg += 360;
  41669. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  41670. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  41671. };
  41672. imgBack.addEventListener("transitionend", onTransitionEnd);
  41673. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  41674. this._loadingDiv.appendChild(imgBack);
  41675. // front image
  41676. var imgFront = new Image();
  41677. 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=";
  41678. imgFront.style.position = "absolute";
  41679. imgFront.style.left = "50%";
  41680. imgFront.style.top = "50%";
  41681. imgFront.style.marginLeft = "-50px";
  41682. imgFront.style.marginTop = "-50px";
  41683. this._loadingDiv.appendChild(imgFront);
  41684. this._resizeLoadingUI();
  41685. window.addEventListener("resize", this._resizeLoadingUI);
  41686. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41687. document.body.appendChild(this._loadingDiv);
  41688. setTimeout(function () {
  41689. _this._loadingDiv.style.opacity = "1";
  41690. imgBack.style.transform = "rotateZ(360deg)";
  41691. imgBack.style.webkitTransform = "rotateZ(360deg)";
  41692. }, 0);
  41693. };
  41694. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  41695. var _this = this;
  41696. if (!this._loadingDiv) {
  41697. return;
  41698. }
  41699. var onTransitionEnd = function () {
  41700. if (!_this._loadingDiv) {
  41701. return;
  41702. }
  41703. document.body.removeChild(_this._loadingDiv);
  41704. window.removeEventListener("resize", _this._resizeLoadingUI);
  41705. _this._loadingDiv = null;
  41706. };
  41707. this._loadingDiv.style.opacity = "0";
  41708. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  41709. };
  41710. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  41711. set: function (text) {
  41712. this._loadingText = text;
  41713. if (this._loadingTextDiv) {
  41714. this._loadingTextDiv.innerHTML = this._loadingText;
  41715. }
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  41721. get: function () {
  41722. return this._loadingDivBackgroundColor;
  41723. },
  41724. set: function (color) {
  41725. this._loadingDivBackgroundColor = color;
  41726. if (!this._loadingDiv) {
  41727. return;
  41728. }
  41729. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  41730. },
  41731. enumerable: true,
  41732. configurable: true
  41733. });
  41734. return DefaultLoadingScreen;
  41735. }());
  41736. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  41737. })(BABYLON || (BABYLON = {}));
  41738. //# sourceMappingURL=babylon.loadingScreen.js.map
  41739. var BABYLON;
  41740. (function (BABYLON) {
  41741. var AudioEngine = (function () {
  41742. function AudioEngine() {
  41743. this._audioContext = null;
  41744. this._audioContextInitialized = false;
  41745. this.canUseWebAudio = false;
  41746. this.WarnedWebAudioUnsupported = false;
  41747. this.unlocked = false;
  41748. this.isMP3supported = false;
  41749. this.isOGGsupported = false;
  41750. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  41751. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  41752. this.canUseWebAudio = true;
  41753. }
  41754. var audioElem = document.createElement('audio');
  41755. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  41756. this.isMP3supported = true;
  41757. }
  41758. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  41759. this.isOGGsupported = true;
  41760. }
  41761. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  41762. this._unlockiOSaudio();
  41763. }
  41764. else {
  41765. this.unlocked = true;
  41766. }
  41767. }
  41768. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  41769. get: function () {
  41770. if (!this._audioContextInitialized) {
  41771. this._initializeAudioContext();
  41772. }
  41773. return this._audioContext;
  41774. },
  41775. enumerable: true,
  41776. configurable: true
  41777. });
  41778. AudioEngine.prototype._unlockiOSaudio = function () {
  41779. var _this = this;
  41780. var unlockaudio = function () {
  41781. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  41782. var source = _this.audioContext.createBufferSource();
  41783. source.buffer = buffer;
  41784. source.connect(_this.audioContext.destination);
  41785. source.start(0);
  41786. setTimeout(function () {
  41787. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  41788. _this.unlocked = true;
  41789. window.removeEventListener('touchend', unlockaudio, false);
  41790. if (_this.onAudioUnlocked) {
  41791. _this.onAudioUnlocked();
  41792. }
  41793. }
  41794. }, 0);
  41795. };
  41796. window.addEventListener('touchend', unlockaudio, false);
  41797. };
  41798. AudioEngine.prototype._initializeAudioContext = function () {
  41799. try {
  41800. if (this.canUseWebAudio) {
  41801. this._audioContext = new AudioContext();
  41802. // create a global volume gain node
  41803. this.masterGain = this._audioContext.createGain();
  41804. this.masterGain.gain.value = 1;
  41805. this.masterGain.connect(this._audioContext.destination);
  41806. this._audioContextInitialized = true;
  41807. }
  41808. }
  41809. catch (e) {
  41810. this.canUseWebAudio = false;
  41811. BABYLON.Tools.Error("Web Audio: " + e.message);
  41812. }
  41813. };
  41814. AudioEngine.prototype.dispose = function () {
  41815. if (this.canUseWebAudio && this._audioContextInitialized) {
  41816. if (this._connectedAnalyser) {
  41817. this._connectedAnalyser.stopDebugCanvas();
  41818. this._connectedAnalyser.dispose();
  41819. this.masterGain.disconnect();
  41820. this.masterGain.connect(this._audioContext.destination);
  41821. this._connectedAnalyser = null;
  41822. }
  41823. this.masterGain.gain.value = 1;
  41824. }
  41825. this.WarnedWebAudioUnsupported = false;
  41826. };
  41827. AudioEngine.prototype.getGlobalVolume = function () {
  41828. if (this.canUseWebAudio && this._audioContextInitialized) {
  41829. return this.masterGain.gain.value;
  41830. }
  41831. else {
  41832. return -1;
  41833. }
  41834. };
  41835. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  41836. if (this.canUseWebAudio && this._audioContextInitialized) {
  41837. this.masterGain.gain.value = newVolume;
  41838. }
  41839. };
  41840. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  41841. if (this._connectedAnalyser) {
  41842. this._connectedAnalyser.stopDebugCanvas();
  41843. }
  41844. if (this.canUseWebAudio && this._audioContextInitialized) {
  41845. this._connectedAnalyser = analyser;
  41846. this.masterGain.disconnect();
  41847. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  41848. }
  41849. };
  41850. return AudioEngine;
  41851. }());
  41852. BABYLON.AudioEngine = AudioEngine;
  41853. })(BABYLON || (BABYLON = {}));
  41854. //# sourceMappingURL=babylon.audioEngine.js.map
  41855. var BABYLON;
  41856. (function (BABYLON) {
  41857. var Sound = (function () {
  41858. /**
  41859. * Create a sound and attach it to a scene
  41860. * @param name Name of your sound
  41861. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  41862. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  41863. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  41864. */
  41865. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  41866. var _this = this;
  41867. this.autoplay = false;
  41868. this.loop = false;
  41869. this.useCustomAttenuation = false;
  41870. this.spatialSound = false;
  41871. this.refDistance = 1;
  41872. this.rolloffFactor = 1;
  41873. this.maxDistance = 100;
  41874. this.distanceModel = "linear";
  41875. this._panningModel = "equalpower";
  41876. this._playbackRate = 1;
  41877. this._streaming = false;
  41878. this._startTime = 0;
  41879. this._startOffset = 0;
  41880. this._position = BABYLON.Vector3.Zero();
  41881. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  41882. this._volume = 1;
  41883. this._isLoaded = false;
  41884. this._isReadyToPlay = false;
  41885. this.isPlaying = false;
  41886. this.isPaused = false;
  41887. this._isDirectional = false;
  41888. // Used if you'd like to create a directional sound.
  41889. // If not set, the sound will be omnidirectional
  41890. this._coneInnerAngle = 360;
  41891. this._coneOuterAngle = 360;
  41892. this._coneOuterGain = 0;
  41893. this._isOutputConnected = false;
  41894. this._urlType = "Unknown";
  41895. this.name = name;
  41896. this._scene = scene;
  41897. this._readyToPlayCallback = readyToPlayCallback;
  41898. // Default custom attenuation function is a linear attenuation
  41899. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  41900. if (currentDistance < maxDistance) {
  41901. return currentVolume * (1 - currentDistance / maxDistance);
  41902. }
  41903. else {
  41904. return 0;
  41905. }
  41906. };
  41907. if (options) {
  41908. this.autoplay = options.autoplay || false;
  41909. this.loop = options.loop || false;
  41910. // if volume === 0, we need another way to check this option
  41911. if (options.volume !== undefined) {
  41912. this._volume = options.volume;
  41913. }
  41914. this.spatialSound = options.spatialSound || false;
  41915. this.maxDistance = options.maxDistance || 100;
  41916. this.useCustomAttenuation = options.useCustomAttenuation || false;
  41917. this.rolloffFactor = options.rolloffFactor || 1;
  41918. this.refDistance = options.refDistance || 1;
  41919. this.distanceModel = options.distanceModel || "linear";
  41920. this._playbackRate = options.playbackRate || 1;
  41921. this._streaming = options.streaming || false;
  41922. }
  41923. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  41924. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  41925. this._soundGain.gain.value = this._volume;
  41926. this._inputAudioNode = this._soundGain;
  41927. this._ouputAudioNode = this._soundGain;
  41928. if (this.spatialSound) {
  41929. this._createSpatialParameters();
  41930. }
  41931. this._scene.mainSoundTrack.AddSound(this);
  41932. var validParameter = true;
  41933. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  41934. if (urlOrArrayBuffer) {
  41935. if (typeof (urlOrArrayBuffer) === "string")
  41936. this._urlType = "String";
  41937. if (Array.isArray(urlOrArrayBuffer))
  41938. this._urlType = "Array";
  41939. if (urlOrArrayBuffer instanceof ArrayBuffer)
  41940. this._urlType = "ArrayBuffer";
  41941. var urls = [];
  41942. var codecSupportedFound = false;
  41943. switch (this._urlType) {
  41944. case "ArrayBuffer":
  41945. if (urlOrArrayBuffer.byteLength > 0) {
  41946. codecSupportedFound = true;
  41947. this._soundLoaded(urlOrArrayBuffer);
  41948. }
  41949. break;
  41950. case "String":
  41951. urls.push(urlOrArrayBuffer);
  41952. case "Array":
  41953. if (urls.length === 0)
  41954. urls = urlOrArrayBuffer;
  41955. // If we found a supported format, we load it immediately and stop the loop
  41956. for (var i = 0; i < urls.length; i++) {
  41957. var url = urls[i];
  41958. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  41959. codecSupportedFound = true;
  41960. }
  41961. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  41962. codecSupportedFound = true;
  41963. }
  41964. if (url.indexOf(".wav", url.length - 4) !== -1) {
  41965. codecSupportedFound = true;
  41966. }
  41967. if (codecSupportedFound) {
  41968. // Loading sound using XHR2
  41969. if (!this._streaming) {
  41970. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  41971. }
  41972. else {
  41973. this._htmlAudioElement = new Audio(url);
  41974. this._htmlAudioElement.controls = false;
  41975. this._htmlAudioElement.loop = this.loop;
  41976. this._htmlAudioElement.crossOrigin = "anonymous";
  41977. this._htmlAudioElement.preload = "auto";
  41978. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  41979. _this._isReadyToPlay = true;
  41980. if (_this.autoplay) {
  41981. _this.play();
  41982. }
  41983. if (_this._readyToPlayCallback) {
  41984. _this._readyToPlayCallback();
  41985. }
  41986. });
  41987. document.body.appendChild(this._htmlAudioElement);
  41988. }
  41989. break;
  41990. }
  41991. }
  41992. break;
  41993. default:
  41994. validParameter = false;
  41995. break;
  41996. }
  41997. if (!validParameter) {
  41998. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  41999. }
  42000. else {
  42001. if (!codecSupportedFound) {
  42002. this._isReadyToPlay = true;
  42003. // Simulating a ready to play event to avoid breaking code path
  42004. if (this._readyToPlayCallback) {
  42005. window.setTimeout(function () {
  42006. _this._readyToPlayCallback();
  42007. }, 1000);
  42008. }
  42009. }
  42010. }
  42011. }
  42012. }
  42013. else {
  42014. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42015. this._scene.mainSoundTrack.AddSound(this);
  42016. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42017. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42018. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42019. }
  42020. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42021. if (this._readyToPlayCallback) {
  42022. window.setTimeout(function () {
  42023. _this._readyToPlayCallback();
  42024. }, 1000);
  42025. }
  42026. }
  42027. }
  42028. Sound.prototype.dispose = function () {
  42029. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42030. if (this.isPlaying) {
  42031. this.stop();
  42032. }
  42033. this._isReadyToPlay = false;
  42034. if (this.soundTrackId === -1) {
  42035. this._scene.mainSoundTrack.RemoveSound(this);
  42036. }
  42037. else {
  42038. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42039. }
  42040. if (this._soundGain) {
  42041. this._soundGain.disconnect();
  42042. this._soundGain = null;
  42043. }
  42044. if (this._soundPanner) {
  42045. this._soundPanner.disconnect();
  42046. this._soundPanner = null;
  42047. }
  42048. if (this._soundSource) {
  42049. this._soundSource.disconnect();
  42050. this._soundSource = null;
  42051. }
  42052. this._audioBuffer = null;
  42053. if (this._htmlAudioElement) {
  42054. this._htmlAudioElement.pause();
  42055. this._htmlAudioElement.src = "";
  42056. document.body.removeChild(this._htmlAudioElement);
  42057. }
  42058. if (this._connectedMesh) {
  42059. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42060. this._connectedMesh = null;
  42061. }
  42062. }
  42063. };
  42064. Sound.prototype.isReady = function () {
  42065. return this._isReadyToPlay;
  42066. };
  42067. Sound.prototype._soundLoaded = function (audioData) {
  42068. var _this = this;
  42069. this._isLoaded = true;
  42070. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42071. _this._audioBuffer = buffer;
  42072. _this._isReadyToPlay = true;
  42073. if (_this.autoplay) {
  42074. _this.play();
  42075. }
  42076. if (_this._readyToPlayCallback) {
  42077. _this._readyToPlayCallback();
  42078. }
  42079. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42080. };
  42081. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42083. this._audioBuffer = audioBuffer;
  42084. this._isReadyToPlay = true;
  42085. }
  42086. };
  42087. Sound.prototype.updateOptions = function (options) {
  42088. if (options) {
  42089. this.loop = options.loop || this.loop;
  42090. this.maxDistance = options.maxDistance || this.maxDistance;
  42091. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42092. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42093. this.refDistance = options.refDistance || this.refDistance;
  42094. this.distanceModel = options.distanceModel || this.distanceModel;
  42095. this._playbackRate = options.playbackRate || this._playbackRate;
  42096. this._updateSpatialParameters();
  42097. if (this.isPlaying) {
  42098. if (this._streaming) {
  42099. this._htmlAudioElement.playbackRate = this._playbackRate;
  42100. }
  42101. else {
  42102. this._soundSource.playbackRate.value = this._playbackRate;
  42103. }
  42104. }
  42105. }
  42106. };
  42107. Sound.prototype._createSpatialParameters = function () {
  42108. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42109. if (this._scene.headphone) {
  42110. this._panningModel = "HRTF";
  42111. }
  42112. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42113. this._updateSpatialParameters();
  42114. this._soundPanner.connect(this._ouputAudioNode);
  42115. this._inputAudioNode = this._soundPanner;
  42116. }
  42117. };
  42118. Sound.prototype._updateSpatialParameters = function () {
  42119. if (this.spatialSound) {
  42120. if (this.useCustomAttenuation) {
  42121. // Tricks to disable in a way embedded Web Audio attenuation
  42122. this._soundPanner.distanceModel = "linear";
  42123. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42124. this._soundPanner.refDistance = 1;
  42125. this._soundPanner.rolloffFactor = 1;
  42126. this._soundPanner.panningModel = this._panningModel;
  42127. }
  42128. else {
  42129. this._soundPanner.distanceModel = this.distanceModel;
  42130. this._soundPanner.maxDistance = this.maxDistance;
  42131. this._soundPanner.refDistance = this.refDistance;
  42132. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42133. this._soundPanner.panningModel = this._panningModel;
  42134. }
  42135. }
  42136. };
  42137. Sound.prototype.switchPanningModelToHRTF = function () {
  42138. this._panningModel = "HRTF";
  42139. this._switchPanningModel();
  42140. };
  42141. Sound.prototype.switchPanningModelToEqualPower = function () {
  42142. this._panningModel = "equalpower";
  42143. this._switchPanningModel();
  42144. };
  42145. Sound.prototype._switchPanningModel = function () {
  42146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42147. this._soundPanner.panningModel = this._panningModel;
  42148. }
  42149. };
  42150. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42151. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42152. if (this._isOutputConnected) {
  42153. this._ouputAudioNode.disconnect();
  42154. }
  42155. this._ouputAudioNode.connect(soundTrackAudioNode);
  42156. this._isOutputConnected = true;
  42157. }
  42158. };
  42159. /**
  42160. * Transform this sound into a directional source
  42161. * @param coneInnerAngle Size of the inner cone in degree
  42162. * @param coneOuterAngle Size of the outer cone in degree
  42163. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42164. */
  42165. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42166. if (coneOuterAngle < coneInnerAngle) {
  42167. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42168. return;
  42169. }
  42170. this._coneInnerAngle = coneInnerAngle;
  42171. this._coneOuterAngle = coneOuterAngle;
  42172. this._coneOuterGain = coneOuterGain;
  42173. this._isDirectional = true;
  42174. if (this.isPlaying && this.loop) {
  42175. this.stop();
  42176. this.play();
  42177. }
  42178. };
  42179. Sound.prototype.setPosition = function (newPosition) {
  42180. this._position = newPosition;
  42181. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42182. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42183. }
  42184. };
  42185. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42186. this._localDirection = newLocalDirection;
  42187. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42188. this._updateDirection();
  42189. }
  42190. };
  42191. Sound.prototype._updateDirection = function () {
  42192. var mat = this._connectedMesh.getWorldMatrix();
  42193. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42194. direction.normalize();
  42195. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42196. };
  42197. Sound.prototype.updateDistanceFromListener = function () {
  42198. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42199. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42200. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42201. }
  42202. };
  42203. Sound.prototype.setAttenuationFunction = function (callback) {
  42204. this._customAttenuationFunction = callback;
  42205. };
  42206. /**
  42207. * Play the sound
  42208. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42209. * @param offset (optional) Start the sound setting it at a specific time
  42210. */
  42211. Sound.prototype.play = function (time, offset) {
  42212. var _this = this;
  42213. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42214. try {
  42215. if (this._startOffset < 0) {
  42216. time = -this._startOffset;
  42217. this._startOffset = 0;
  42218. }
  42219. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42220. if (!this._soundSource || !this._streamingSource) {
  42221. if (this.spatialSound) {
  42222. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42223. if (this._isDirectional) {
  42224. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42225. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42226. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42227. if (this._connectedMesh) {
  42228. this._updateDirection();
  42229. }
  42230. else {
  42231. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42232. }
  42233. }
  42234. }
  42235. }
  42236. if (this._streaming) {
  42237. if (!this._streamingSource) {
  42238. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42239. this._htmlAudioElement.onended = function () { _this._onended(); };
  42240. this._htmlAudioElement.playbackRate = this._playbackRate;
  42241. }
  42242. this._streamingSource.disconnect();
  42243. this._streamingSource.connect(this._inputAudioNode);
  42244. this._htmlAudioElement.play();
  42245. }
  42246. else {
  42247. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42248. this._soundSource.buffer = this._audioBuffer;
  42249. this._soundSource.connect(this._inputAudioNode);
  42250. this._soundSource.loop = this.loop;
  42251. this._soundSource.playbackRate.value = this._playbackRate;
  42252. this._soundSource.onended = function () { _this._onended(); };
  42253. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42254. }
  42255. this._startTime = startTime;
  42256. this.isPlaying = true;
  42257. this.isPaused = false;
  42258. }
  42259. catch (ex) {
  42260. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42261. }
  42262. }
  42263. };
  42264. Sound.prototype._onended = function () {
  42265. this.isPlaying = false;
  42266. if (this.onended) {
  42267. this.onended();
  42268. }
  42269. };
  42270. /**
  42271. * Stop the sound
  42272. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  42273. */
  42274. Sound.prototype.stop = function (time) {
  42275. if (this.isPlaying) {
  42276. if (this._streaming) {
  42277. this._htmlAudioElement.pause();
  42278. // Test needed for Firefox or it will generate an Invalid State Error
  42279. if (this._htmlAudioElement.currentTime > 0) {
  42280. this._htmlAudioElement.currentTime = 0;
  42281. }
  42282. }
  42283. else {
  42284. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42285. this._soundSource.stop(stopTime);
  42286. this._soundSource.onended = null;
  42287. if (!this.isPaused) {
  42288. this._startOffset = 0;
  42289. }
  42290. }
  42291. this.isPlaying = false;
  42292. }
  42293. };
  42294. Sound.prototype.pause = function () {
  42295. if (this.isPlaying) {
  42296. this.isPaused = true;
  42297. if (this._streaming) {
  42298. this._htmlAudioElement.pause();
  42299. }
  42300. else {
  42301. this.stop(0);
  42302. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  42303. }
  42304. }
  42305. };
  42306. Sound.prototype.setVolume = function (newVolume, time) {
  42307. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42308. if (time) {
  42309. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  42310. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  42311. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  42312. }
  42313. else {
  42314. this._soundGain.gain.value = newVolume;
  42315. }
  42316. }
  42317. this._volume = newVolume;
  42318. };
  42319. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  42320. this._playbackRate = newPlaybackRate;
  42321. if (this.isPlaying) {
  42322. if (this._streaming) {
  42323. this._htmlAudioElement.playbackRate = this._playbackRate;
  42324. }
  42325. else {
  42326. this._soundSource.playbackRate.value = this._playbackRate;
  42327. }
  42328. }
  42329. };
  42330. Sound.prototype.getVolume = function () {
  42331. return this._volume;
  42332. };
  42333. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  42334. var _this = this;
  42335. if (this._connectedMesh) {
  42336. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42337. this._registerFunc = null;
  42338. }
  42339. this._connectedMesh = meshToConnectTo;
  42340. if (!this.spatialSound) {
  42341. this.spatialSound = true;
  42342. this._createSpatialParameters();
  42343. if (this.isPlaying && this.loop) {
  42344. this.stop();
  42345. this.play();
  42346. }
  42347. }
  42348. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  42349. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  42350. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  42351. };
  42352. Sound.prototype.detachFromMesh = function () {
  42353. if (this._connectedMesh) {
  42354. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42355. this._registerFunc = null;
  42356. this._connectedMesh = null;
  42357. }
  42358. };
  42359. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  42360. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  42361. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  42362. this._updateDirection();
  42363. }
  42364. };
  42365. Sound.prototype.clone = function () {
  42366. var _this = this;
  42367. if (!this._streaming) {
  42368. var setBufferAndRun = function () {
  42369. if (_this._isReadyToPlay) {
  42370. clonedSound._audioBuffer = _this.getAudioBuffer();
  42371. clonedSound._isReadyToPlay = true;
  42372. if (clonedSound.autoplay) {
  42373. clonedSound.play();
  42374. }
  42375. }
  42376. else {
  42377. window.setTimeout(setBufferAndRun, 300);
  42378. }
  42379. };
  42380. var currentOptions = {
  42381. autoplay: this.autoplay, loop: this.loop,
  42382. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  42383. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  42384. refDistance: this.refDistance, distanceModel: this.distanceModel
  42385. };
  42386. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  42387. if (this.useCustomAttenuation) {
  42388. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  42389. }
  42390. clonedSound.setPosition(this._position);
  42391. clonedSound.setPlaybackRate(this._playbackRate);
  42392. setBufferAndRun();
  42393. return clonedSound;
  42394. }
  42395. else {
  42396. return null;
  42397. }
  42398. };
  42399. Sound.prototype.getAudioBuffer = function () {
  42400. return this._audioBuffer;
  42401. };
  42402. Sound.prototype.serialize = function () {
  42403. var serializationObject = {
  42404. name: this.name,
  42405. url: this.name,
  42406. autoplay: this.autoplay,
  42407. loop: this.loop,
  42408. volume: this._volume,
  42409. spatialSound: this.spatialSound,
  42410. maxDistance: this.maxDistance,
  42411. rolloffFactor: this.rolloffFactor,
  42412. refDistance: this.refDistance,
  42413. distanceModel: this.distanceModel,
  42414. playbackRate: this._playbackRate,
  42415. panningModel: this._panningModel,
  42416. soundTrackId: this.soundTrackId
  42417. };
  42418. if (this.spatialSound) {
  42419. if (this._connectedMesh)
  42420. serializationObject.connectedMeshId = this._connectedMesh.id;
  42421. serializationObject.position = this._position.asArray();
  42422. serializationObject.refDistance = this.refDistance;
  42423. serializationObject.distanceModel = this.distanceModel;
  42424. serializationObject.isDirectional = this._isDirectional;
  42425. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  42426. serializationObject.coneInnerAngle = this._coneInnerAngle;
  42427. serializationObject.coneOuterAngle = this._coneOuterAngle;
  42428. serializationObject.coneOuterGain = this._coneOuterGain;
  42429. }
  42430. return serializationObject;
  42431. };
  42432. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  42433. var soundName = parsedSound.name;
  42434. var soundUrl;
  42435. if (parsedSound.url) {
  42436. soundUrl = rootUrl + parsedSound.url;
  42437. }
  42438. else {
  42439. soundUrl = rootUrl + soundName;
  42440. }
  42441. var options = {
  42442. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  42443. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  42444. rolloffFactor: parsedSound.rolloffFactor,
  42445. refDistance: parsedSound.refDistance,
  42446. distanceModel: parsedSound.distanceModel,
  42447. playbackRate: parsedSound.playbackRate
  42448. };
  42449. var newSound;
  42450. if (!sourceSound) {
  42451. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  42452. scene._addPendingData(newSound);
  42453. }
  42454. else {
  42455. var setBufferAndRun = function () {
  42456. if (sourceSound._isReadyToPlay) {
  42457. newSound._audioBuffer = sourceSound.getAudioBuffer();
  42458. newSound._isReadyToPlay = true;
  42459. if (newSound.autoplay) {
  42460. newSound.play();
  42461. }
  42462. }
  42463. else {
  42464. window.setTimeout(setBufferAndRun, 300);
  42465. }
  42466. };
  42467. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  42468. setBufferAndRun();
  42469. }
  42470. if (parsedSound.position) {
  42471. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  42472. newSound.setPosition(soundPosition);
  42473. }
  42474. if (parsedSound.isDirectional) {
  42475. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  42476. if (parsedSound.localDirectionToMesh) {
  42477. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  42478. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  42479. }
  42480. }
  42481. if (parsedSound.connectedMeshId) {
  42482. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  42483. if (connectedMesh) {
  42484. newSound.attachToMesh(connectedMesh);
  42485. }
  42486. }
  42487. return newSound;
  42488. };
  42489. return Sound;
  42490. }());
  42491. BABYLON.Sound = Sound;
  42492. })(BABYLON || (BABYLON = {}));
  42493. //# sourceMappingURL=babylon.sound.js.map
  42494. var BABYLON;
  42495. (function (BABYLON) {
  42496. var SoundTrack = (function () {
  42497. function SoundTrack(scene, options) {
  42498. this.id = -1;
  42499. this._isMainTrack = false;
  42500. this._isInitialized = false;
  42501. this._scene = scene;
  42502. this.soundCollection = new Array();
  42503. this._options = options;
  42504. if (!this._isMainTrack) {
  42505. this._scene.soundTracks.push(this);
  42506. this.id = this._scene.soundTracks.length - 1;
  42507. }
  42508. }
  42509. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  42510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42511. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  42512. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  42513. if (this._options) {
  42514. if (this._options.volume) {
  42515. this._outputAudioNode.gain.value = this._options.volume;
  42516. }
  42517. if (this._options.mainTrack) {
  42518. this._isMainTrack = this._options.mainTrack;
  42519. }
  42520. }
  42521. this._isInitialized = true;
  42522. }
  42523. };
  42524. SoundTrack.prototype.dispose = function () {
  42525. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42526. if (this._connectedAnalyser) {
  42527. this._connectedAnalyser.stopDebugCanvas();
  42528. }
  42529. while (this.soundCollection.length) {
  42530. this.soundCollection[0].dispose();
  42531. }
  42532. if (this._outputAudioNode) {
  42533. this._outputAudioNode.disconnect();
  42534. }
  42535. this._outputAudioNode = null;
  42536. }
  42537. };
  42538. SoundTrack.prototype.AddSound = function (sound) {
  42539. if (!this._isInitialized) {
  42540. this._initializeSoundTrackAudioGraph();
  42541. }
  42542. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42543. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  42544. }
  42545. if (sound.soundTrackId) {
  42546. if (sound.soundTrackId === -1) {
  42547. this._scene.mainSoundTrack.RemoveSound(sound);
  42548. }
  42549. else {
  42550. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  42551. }
  42552. }
  42553. this.soundCollection.push(sound);
  42554. sound.soundTrackId = this.id;
  42555. };
  42556. SoundTrack.prototype.RemoveSound = function (sound) {
  42557. var index = this.soundCollection.indexOf(sound);
  42558. if (index !== -1) {
  42559. this.soundCollection.splice(index, 1);
  42560. }
  42561. };
  42562. SoundTrack.prototype.setVolume = function (newVolume) {
  42563. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42564. this._outputAudioNode.gain.value = newVolume;
  42565. }
  42566. };
  42567. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  42568. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42569. for (var i = 0; i < this.soundCollection.length; i++) {
  42570. this.soundCollection[i].switchPanningModelToHRTF();
  42571. }
  42572. }
  42573. };
  42574. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  42575. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42576. for (var i = 0; i < this.soundCollection.length; i++) {
  42577. this.soundCollection[i].switchPanningModelToEqualPower();
  42578. }
  42579. }
  42580. };
  42581. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  42582. if (this._connectedAnalyser) {
  42583. this._connectedAnalyser.stopDebugCanvas();
  42584. }
  42585. this._connectedAnalyser = analyser;
  42586. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42587. this._outputAudioNode.disconnect();
  42588. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  42589. }
  42590. };
  42591. return SoundTrack;
  42592. }());
  42593. BABYLON.SoundTrack = SoundTrack;
  42594. })(BABYLON || (BABYLON = {}));
  42595. //# sourceMappingURL=babylon.soundtrack.js.map
  42596. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  42597. /// <reference path="..\Math\babylon.math.ts" />
  42598. var BABYLON;
  42599. (function (BABYLON) {
  42600. /**
  42601. * Special Glow Blur post process only blurring the alpha channel
  42602. * It enforces keeping the most luminous color in the color channel.
  42603. */
  42604. var GlowBlurPostProcess = (function (_super) {
  42605. __extends(GlowBlurPostProcess, _super);
  42606. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  42607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  42608. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  42609. _this.direction = direction;
  42610. _this.blurWidth = blurWidth;
  42611. _this.onApplyObservable.add(function (effect) {
  42612. effect.setFloat2("screenSize", _this.width, _this.height);
  42613. effect.setVector2("direction", _this.direction);
  42614. effect.setFloat("blurWidth", _this.blurWidth);
  42615. });
  42616. return _this;
  42617. }
  42618. return GlowBlurPostProcess;
  42619. }(BABYLON.PostProcess));
  42620. /**
  42621. * The highlight layer Helps adding a glow effect around a mesh.
  42622. *
  42623. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  42624. * glowy meshes to your scene.
  42625. *
  42626. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  42627. */
  42628. var HighlightLayer = (function () {
  42629. /**
  42630. * Instantiates a new highlight Layer and references it to the scene..
  42631. * @param name The name of the layer
  42632. * @param scene The scene to use the layer in
  42633. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  42634. */
  42635. function HighlightLayer(name, scene, options) {
  42636. this.name = name;
  42637. this._vertexBuffers = {};
  42638. this._mainTextureDesiredSize = { width: 0, height: 0 };
  42639. this._meshes = {};
  42640. this._maxSize = 0;
  42641. this._shouldRender = false;
  42642. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  42643. this._excludedMeshes = {};
  42644. /**
  42645. * Specifies whether or not the inner glow is ACTIVE in the layer.
  42646. */
  42647. this.innerGlow = true;
  42648. /**
  42649. * Specifies whether or not the outer glow is ACTIVE in the layer.
  42650. */
  42651. this.outerGlow = true;
  42652. /**
  42653. * Specifies wether the highlight layer is enabled or not.
  42654. */
  42655. this.isEnabled = true;
  42656. /**
  42657. * An event triggered when the highlight layer has been disposed.
  42658. * @type {BABYLON.Observable}
  42659. */
  42660. this.onDisposeObservable = new BABYLON.Observable();
  42661. /**
  42662. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  42663. * @type {BABYLON.Observable}
  42664. */
  42665. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  42666. /**
  42667. * An event triggered when the highlight layer is being blurred.
  42668. * @type {BABYLON.Observable}
  42669. */
  42670. this.onBeforeBlurObservable = new BABYLON.Observable();
  42671. /**
  42672. * An event triggered when the highlight layer has been blurred.
  42673. * @type {BABYLON.Observable}
  42674. */
  42675. this.onAfterBlurObservable = new BABYLON.Observable();
  42676. /**
  42677. * An event triggered when the glowing blurred texture is being merged in the scene.
  42678. * @type {BABYLON.Observable}
  42679. */
  42680. this.onBeforeComposeObservable = new BABYLON.Observable();
  42681. /**
  42682. * An event triggered when the glowing blurred texture has been merged in the scene.
  42683. * @type {BABYLON.Observable}
  42684. */
  42685. this.onAfterComposeObservable = new BABYLON.Observable();
  42686. /**
  42687. * An event triggered when the highlight layer changes its size.
  42688. * @type {BABYLON.Observable}
  42689. */
  42690. this.onSizeChangedObservable = new BABYLON.Observable();
  42691. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42692. var engine = scene.getEngine();
  42693. this._engine = engine;
  42694. this._maxSize = this._engine.getCaps().maxTextureSize;
  42695. this._scene.highlightLayers.push(this);
  42696. // Warn on stencil.
  42697. if (!this._engine.isStencilEnable) {
  42698. 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 }");
  42699. }
  42700. // Adapt options
  42701. this._options = options || {
  42702. mainTextureRatio: 0.25,
  42703. blurTextureSizeRatio: 0.5,
  42704. blurHorizontalSize: 1,
  42705. blurVerticalSize: 1,
  42706. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  42707. };
  42708. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  42709. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  42710. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  42711. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  42712. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  42713. // VBO
  42714. var vertices = [];
  42715. vertices.push(1, 1);
  42716. vertices.push(-1, 1);
  42717. vertices.push(-1, -1);
  42718. vertices.push(1, -1);
  42719. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  42720. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  42721. // Indices
  42722. var indices = [];
  42723. indices.push(0);
  42724. indices.push(1);
  42725. indices.push(2);
  42726. indices.push(0);
  42727. indices.push(2);
  42728. indices.push(3);
  42729. this._indexBuffer = engine.createIndexBuffer(indices);
  42730. // Effect
  42731. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  42732. // Render target
  42733. this.setMainTextureSize();
  42734. // Create Textures and post processes
  42735. this.createTextureAndPostProcesses();
  42736. }
  42737. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  42738. /**
  42739. * Gets the horizontal size of the blur.
  42740. */
  42741. get: function () {
  42742. return this._horizontalBlurPostprocess.blurWidth;
  42743. },
  42744. /**
  42745. * Specifies the horizontal size of the blur.
  42746. */
  42747. set: function (value) {
  42748. this._horizontalBlurPostprocess.blurWidth = value;
  42749. },
  42750. enumerable: true,
  42751. configurable: true
  42752. });
  42753. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  42754. /**
  42755. * Gets the vertical size of the blur.
  42756. */
  42757. get: function () {
  42758. return this._verticalBlurPostprocess.blurWidth;
  42759. },
  42760. /**
  42761. * Specifies the vertical size of the blur.
  42762. */
  42763. set: function (value) {
  42764. this._verticalBlurPostprocess.blurWidth = value;
  42765. },
  42766. enumerable: true,
  42767. configurable: true
  42768. });
  42769. Object.defineProperty(HighlightLayer.prototype, "camera", {
  42770. /**
  42771. * Gets the camera attached to the layer.
  42772. */
  42773. get: function () {
  42774. return this._options.camera;
  42775. },
  42776. enumerable: true,
  42777. configurable: true
  42778. });
  42779. /**
  42780. * Creates the render target textures and post processes used in the highlight layer.
  42781. */
  42782. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  42783. var _this = this;
  42784. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  42785. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  42786. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  42787. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  42788. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  42789. width: this._mainTextureDesiredSize.width,
  42790. height: this._mainTextureDesiredSize.height
  42791. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42792. this._mainTexture.activeCamera = this._options.camera;
  42793. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42794. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42795. this._mainTexture.anisotropicFilteringLevel = 1;
  42796. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42797. this._mainTexture.renderParticles = false;
  42798. this._mainTexture.renderList = null;
  42799. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  42800. width: blurTextureWidth,
  42801. height: blurTextureHeight
  42802. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  42803. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42804. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42805. this._blurTexture.anisotropicFilteringLevel = 16;
  42806. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  42807. this._blurTexture.renderParticles = false;
  42808. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42809. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  42810. effect.setTexture("textureSampler", _this._mainTexture);
  42811. });
  42812. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  42813. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42814. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42815. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42816. });
  42817. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42818. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42819. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42820. });
  42821. }
  42822. else {
  42823. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42824. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  42825. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42826. });
  42827. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  42828. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  42829. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  42830. });
  42831. }
  42832. this._mainTexture.onAfterUnbindObservable.add(function () {
  42833. _this.onBeforeBlurObservable.notifyObservers(_this);
  42834. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  42835. _this.onAfterBlurObservable.notifyObservers(_this);
  42836. });
  42837. // Custom render function
  42838. var renderSubMesh = function (subMesh) {
  42839. var mesh = subMesh.getRenderingMesh();
  42840. var scene = _this._scene;
  42841. var engine = scene.getEngine();
  42842. // Culling
  42843. engine.setState(subMesh.getMaterial().backFaceCulling);
  42844. // Managing instances
  42845. var batch = mesh._getInstancesRenderList(subMesh._id);
  42846. if (batch.mustReturn) {
  42847. return;
  42848. }
  42849. // Excluded Mesh
  42850. if (_this._excludedMeshes[mesh.uniqueId]) {
  42851. return;
  42852. }
  42853. ;
  42854. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42855. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  42856. var material = subMesh.getMaterial();
  42857. var emissiveTexture = null;
  42858. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  42859. emissiveTexture = material.emissiveTexture;
  42860. }
  42861. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  42862. engine.enableEffect(_this._glowMapGenerationEffect);
  42863. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  42864. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  42865. if (highlightLayerMesh) {
  42866. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  42867. }
  42868. else {
  42869. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  42870. }
  42871. // Alpha test
  42872. if (material && material.needAlphaTesting()) {
  42873. var alphaTexture = material.getAlphaTestTexture();
  42874. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  42875. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42876. }
  42877. // Glow emissive only
  42878. if (emissiveTexture) {
  42879. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  42880. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  42881. }
  42882. // Bones
  42883. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42884. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42885. }
  42886. // Draw
  42887. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  42888. }
  42889. else {
  42890. // Need to reset refresh rate of the shadowMap
  42891. _this._mainTexture.resetRefreshCounter();
  42892. }
  42893. };
  42894. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42895. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  42896. var index;
  42897. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42898. renderSubMesh(opaqueSubMeshes.data[index]);
  42899. }
  42900. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42901. renderSubMesh(alphaTestSubMeshes.data[index]);
  42902. }
  42903. for (index = 0; index < transparentSubMeshes.length; index++) {
  42904. renderSubMesh(transparentSubMeshes.data[index]);
  42905. }
  42906. };
  42907. this._mainTexture.onClearObservable.add(function (engine) {
  42908. engine.clear(HighlightLayer.neutralColor, true, true, true);
  42909. });
  42910. };
  42911. /**
  42912. * Checks for the readiness of the element composing the layer.
  42913. * @param subMesh the mesh to check for
  42914. * @param useInstances specify wether or not to use instances to render the mesh
  42915. * @param emissiveTexture the associated emissive texture used to generate the glow
  42916. * @return true if ready otherwise, false
  42917. */
  42918. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  42919. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  42920. return false;
  42921. }
  42922. var defines = [];
  42923. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42924. var mesh = subMesh.getMesh();
  42925. var material = subMesh.getMaterial();
  42926. var uv1 = false;
  42927. var uv2 = false;
  42928. // Alpha test
  42929. if (material && material.needAlphaTesting()) {
  42930. var alphaTexture = material.getAlphaTestTexture();
  42931. if (alphaTexture) {
  42932. defines.push("#define ALPHATEST");
  42933. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42934. alphaTexture.coordinatesIndex === 1) {
  42935. defines.push("#define DIFFUSEUV2");
  42936. uv2 = true;
  42937. }
  42938. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42939. defines.push("#define DIFFUSEUV1");
  42940. uv1 = true;
  42941. }
  42942. }
  42943. }
  42944. // Emissive
  42945. if (emissiveTexture) {
  42946. defines.push("#define EMISSIVE");
  42947. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  42948. emissiveTexture.coordinatesIndex === 1) {
  42949. defines.push("#define EMISSIVEUV2");
  42950. uv2 = true;
  42951. }
  42952. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42953. defines.push("#define EMISSIVEUV1");
  42954. uv1 = true;
  42955. }
  42956. }
  42957. if (uv1) {
  42958. attribs.push(BABYLON.VertexBuffer.UVKind);
  42959. defines.push("#define UV1");
  42960. }
  42961. if (uv2) {
  42962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42963. defines.push("#define UV2");
  42964. }
  42965. // Bones
  42966. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42969. if (mesh.numBoneInfluencers > 4) {
  42970. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42971. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42972. }
  42973. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42974. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42975. }
  42976. else {
  42977. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42978. }
  42979. // Instances
  42980. if (useInstances) {
  42981. defines.push("#define INSTANCES");
  42982. attribs.push("world0");
  42983. attribs.push("world1");
  42984. attribs.push("world2");
  42985. attribs.push("world3");
  42986. }
  42987. // Get correct effect
  42988. var join = defines.join("\n");
  42989. if (this._cachedDefines !== join) {
  42990. this._cachedDefines = join;
  42991. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  42992. }
  42993. return this._glowMapGenerationEffect.isReady();
  42994. };
  42995. /**
  42996. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  42997. */
  42998. HighlightLayer.prototype.render = function () {
  42999. var currentEffect = this._glowMapMergeEffect;
  43000. // Check
  43001. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  43002. return;
  43003. var engine = this._scene.getEngine();
  43004. this.onBeforeComposeObservable.notifyObservers(this);
  43005. // Render
  43006. engine.enableEffect(currentEffect);
  43007. engine.setState(false);
  43008. // Cache
  43009. var previousStencilBuffer = engine.getStencilBuffer();
  43010. var previousStencilFunction = engine.getStencilFunction();
  43011. var previousStencilMask = engine.getStencilMask();
  43012. var previousAlphaMode = engine.getAlphaMode();
  43013. // Texture
  43014. currentEffect.setTexture("textureSampler", this._blurTexture);
  43015. // VBOs
  43016. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  43017. // Draw order
  43018. engine.setAlphaMode(this._options.alphaBlendingMode);
  43019. engine.setStencilMask(0x00);
  43020. engine.setStencilBuffer(true);
  43021. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  43022. if (this.outerGlow) {
  43023. currentEffect.setFloat("offset", 0);
  43024. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  43025. engine.draw(true, 0, 6);
  43026. }
  43027. if (this.innerGlow) {
  43028. currentEffect.setFloat("offset", 1);
  43029. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  43030. engine.draw(true, 0, 6);
  43031. }
  43032. // Restore Cache
  43033. engine.setStencilFunction(previousStencilFunction);
  43034. engine.setStencilMask(previousStencilMask);
  43035. engine.setAlphaMode(previousAlphaMode);
  43036. engine.setStencilBuffer(previousStencilBuffer);
  43037. this.onAfterComposeObservable.notifyObservers(this);
  43038. // Handle size changes.
  43039. var size = this._mainTexture.getSize();
  43040. this.setMainTextureSize();
  43041. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  43042. // Recreate RTT and post processes on size change.
  43043. this.onSizeChangedObservable.notifyObservers(this);
  43044. this.disposeTextureAndPostProcesses();
  43045. this.createTextureAndPostProcesses();
  43046. }
  43047. };
  43048. /**
  43049. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  43050. * @param mesh The mesh to exclude from the highlight layer
  43051. */
  43052. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  43053. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43054. if (!meshExcluded) {
  43055. this._excludedMeshes[mesh.uniqueId] = {
  43056. mesh: mesh,
  43057. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  43058. mesh.getEngine().setStencilBuffer(false);
  43059. }),
  43060. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  43061. mesh.getEngine().setStencilBuffer(true);
  43062. }),
  43063. };
  43064. }
  43065. };
  43066. /**
  43067. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  43068. * @param mesh The mesh to highlight
  43069. */
  43070. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  43071. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43072. if (meshExcluded) {
  43073. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  43074. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  43075. }
  43076. this._excludedMeshes[mesh.uniqueId] = undefined;
  43077. };
  43078. /**
  43079. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  43080. * @param mesh The mesh to highlight
  43081. * @param color The color of the highlight
  43082. * @param glowEmissiveOnly Extract the glow from the emissive texture
  43083. */
  43084. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  43085. var _this = this;
  43086. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  43087. var meshHighlight = this._meshes[mesh.uniqueId];
  43088. if (meshHighlight) {
  43089. meshHighlight.color = color;
  43090. }
  43091. else {
  43092. this._meshes[mesh.uniqueId] = {
  43093. mesh: mesh,
  43094. color: color,
  43095. // Lambda required for capture due to Observable this context
  43096. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  43097. if (_this._excludedMeshes[mesh.uniqueId]) {
  43098. _this.defaultStencilReference(mesh);
  43099. }
  43100. else {
  43101. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  43102. }
  43103. }),
  43104. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  43105. glowEmissiveOnly: glowEmissiveOnly
  43106. };
  43107. }
  43108. this._shouldRender = true;
  43109. };
  43110. /**
  43111. * Remove a mesh from the highlight layer in order to make it stop glowing.
  43112. * @param mesh The mesh to highlight
  43113. */
  43114. HighlightLayer.prototype.removeMesh = function (mesh) {
  43115. var meshHighlight = this._meshes[mesh.uniqueId];
  43116. if (meshHighlight) {
  43117. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43118. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43119. }
  43120. this._meshes[mesh.uniqueId] = undefined;
  43121. this._shouldRender = false;
  43122. for (var meshHighlightToCheck in this._meshes) {
  43123. if (meshHighlightToCheck) {
  43124. this._shouldRender = true;
  43125. break;
  43126. }
  43127. }
  43128. };
  43129. /**
  43130. * Returns true if the layer contains information to display, otherwise false.
  43131. */
  43132. HighlightLayer.prototype.shouldRender = function () {
  43133. return this.isEnabled && this._shouldRender;
  43134. };
  43135. /**
  43136. * Sets the main texture desired size which is the closest power of two
  43137. * of the engine canvas size.
  43138. */
  43139. HighlightLayer.prototype.setMainTextureSize = function () {
  43140. if (this._options.mainTextureFixedSize) {
  43141. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  43142. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  43143. }
  43144. else {
  43145. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  43146. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  43147. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  43148. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  43149. }
  43150. };
  43151. /**
  43152. * Force the stencil to the normal expected value for none glowing parts
  43153. */
  43154. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  43155. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  43156. };
  43157. /**
  43158. * Dispose only the render target textures and post process.
  43159. */
  43160. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  43161. this._blurTexture.dispose();
  43162. this._mainTexture.dispose();
  43163. this._downSamplePostprocess.dispose();
  43164. this._horizontalBlurPostprocess.dispose();
  43165. this._verticalBlurPostprocess.dispose();
  43166. };
  43167. /**
  43168. * Dispose the highlight layer and free resources.
  43169. */
  43170. HighlightLayer.prototype.dispose = function () {
  43171. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43172. if (vertexBuffer) {
  43173. vertexBuffer.dispose();
  43174. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43175. }
  43176. if (this._indexBuffer) {
  43177. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43178. this._indexBuffer = null;
  43179. }
  43180. // Clean textures and post processes
  43181. this.disposeTextureAndPostProcesses();
  43182. // Clean mesh references
  43183. for (var id in this._meshes) {
  43184. var meshHighlight = this._meshes[id];
  43185. if (meshHighlight && meshHighlight.mesh) {
  43186. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43187. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43188. }
  43189. }
  43190. this._meshes = null;
  43191. for (var id in this._excludedMeshes) {
  43192. var meshHighlight = this._excludedMeshes[id];
  43193. if (meshHighlight) {
  43194. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  43195. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  43196. }
  43197. }
  43198. this._excludedMeshes = null;
  43199. // Remove from scene
  43200. var index = this._scene.highlightLayers.indexOf(this, 0);
  43201. if (index > -1) {
  43202. this._scene.highlightLayers.splice(index, 1);
  43203. }
  43204. // Callback
  43205. this.onDisposeObservable.notifyObservers(this);
  43206. this.onDisposeObservable.clear();
  43207. this.onBeforeRenderMainTextureObservable.clear();
  43208. this.onBeforeBlurObservable.clear();
  43209. this.onBeforeComposeObservable.clear();
  43210. this.onAfterComposeObservable.clear();
  43211. this.onSizeChangedObservable.clear();
  43212. };
  43213. return HighlightLayer;
  43214. }());
  43215. /**
  43216. * The neutral color used during the preparation of the glow effect.
  43217. * This is black by default as the blend operation is a blend operation.
  43218. */
  43219. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  43220. /**
  43221. * Stencil value used for glowing meshes.
  43222. */
  43223. HighlightLayer.glowingMeshStencilReference = 0x02;
  43224. /**
  43225. * Stencil value used for the other meshes in the scene.
  43226. */
  43227. HighlightLayer.normalMeshStencilReference = 0x01;
  43228. BABYLON.HighlightLayer = HighlightLayer;
  43229. })(BABYLON || (BABYLON = {}));
  43230. //# sourceMappingURL=babylon.highlightlayer.js.map
  43231. var BABYLON;
  43232. (function (BABYLON) {
  43233. var SIMDVector3 = (function () {
  43234. function SIMDVector3() {
  43235. }
  43236. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  43237. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  43238. };
  43239. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  43240. var m = transformation.m;
  43241. var m0 = SIMD.Float32x4.load(m, 0);
  43242. var m1 = SIMD.Float32x4.load(m, 4);
  43243. var m2 = SIMD.Float32x4.load(m, 8);
  43244. var m3 = SIMD.Float32x4.load(m, 12);
  43245. 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));
  43246. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  43247. result.x = SIMD.Float32x4.extractLane(r, 0);
  43248. result.y = SIMD.Float32x4.extractLane(r, 1);
  43249. result.z = SIMD.Float32x4.extractLane(r, 2);
  43250. };
  43251. return SIMDVector3;
  43252. }());
  43253. var SIMDMatrix = (function () {
  43254. function SIMDMatrix() {
  43255. }
  43256. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  43257. var tm = this.m;
  43258. var om = other.m;
  43259. var m0 = SIMD.Float32x4.load(om, 0);
  43260. var m1 = SIMD.Float32x4.load(om, 4);
  43261. var m2 = SIMD.Float32x4.load(om, 8);
  43262. var m3 = SIMD.Float32x4.load(om, 12);
  43263. for (var i = 0; i < 16; i += 4) {
  43264. 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)))));
  43265. }
  43266. return this;
  43267. };
  43268. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  43269. var src = this.m;
  43270. var dest = other.m;
  43271. // Load the 4 rows
  43272. var src0 = SIMD.Float32x4.load(src, 0);
  43273. var src1 = SIMD.Float32x4.load(src, 4);
  43274. var src2 = SIMD.Float32x4.load(src, 8);
  43275. var src3 = SIMD.Float32x4.load(src, 12);
  43276. // Transpose the source matrix. Sort of. Not a true transpose operation
  43277. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  43278. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  43279. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  43280. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  43281. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  43282. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  43283. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  43284. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  43285. // This is a true transposition, but it will lead to an incorrect result
  43286. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  43287. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  43288. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43289. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43290. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  43291. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  43292. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  43293. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  43294. // ----
  43295. tmp1 = SIMD.Float32x4.mul(row2, row3);
  43296. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43297. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  43298. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  43299. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43300. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  43301. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  43302. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  43303. // ----
  43304. tmp1 = SIMD.Float32x4.mul(row1, row2);
  43305. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43306. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  43307. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  43308. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43309. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  43310. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  43311. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  43312. // ----
  43313. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  43314. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43315. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  43316. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  43317. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  43318. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43319. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  43320. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  43321. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  43322. // ----
  43323. tmp1 = SIMD.Float32x4.mul(row0, row1);
  43324. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43325. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  43326. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  43327. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43328. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  43329. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  43330. // ----
  43331. tmp1 = SIMD.Float32x4.mul(row0, row3);
  43332. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43333. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  43334. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  43335. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43336. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  43337. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  43338. // ----
  43339. tmp1 = SIMD.Float32x4.mul(row0, row2);
  43340. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  43341. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  43342. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  43343. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  43344. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  43345. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  43346. // Compute determinant
  43347. var det = SIMD.Float32x4.mul(row0, minor0);
  43348. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  43349. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  43350. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  43351. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  43352. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  43353. // These shuffles aren't necessary if the faulty transposition is done
  43354. // up at the top of this function.
  43355. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  43356. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  43357. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  43358. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  43359. // Compute final values by multiplying with 1/det
  43360. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  43361. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  43362. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  43363. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  43364. return this;
  43365. };
  43366. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  43367. var out = result.m;
  43368. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  43369. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  43370. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  43371. // cc.kmVec3Subtract(f, pCenter, pEye);
  43372. var f = SIMD.Float32x4.sub(center, eye);
  43373. // cc.kmVec3Normalize(f, f);
  43374. var tmp = SIMD.Float32x4.mul(f, f);
  43375. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  43376. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  43377. // cc.kmVec3Assign(up, pUp);
  43378. // cc.kmVec3Normalize(up, up);
  43379. tmp = SIMD.Float32x4.mul(up, up);
  43380. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  43381. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  43382. // cc.kmVec3Cross(s, f, up);
  43383. 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)));
  43384. // cc.kmVec3Normalize(s, s);
  43385. tmp = SIMD.Float32x4.mul(s, s);
  43386. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  43387. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  43388. // cc.kmVec3Cross(u, s, f);
  43389. 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)));
  43390. // cc.kmVec3Normalize(s, s);
  43391. tmp = SIMD.Float32x4.mul(s, s);
  43392. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  43393. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  43394. var zero = SIMD.Float32x4.splat(0.0);
  43395. s = SIMD.Float32x4.neg(s);
  43396. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  43397. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  43398. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  43399. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  43400. 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);
  43401. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  43402. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  43403. 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)))));
  43404. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  43405. 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)))));
  43406. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  43407. 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)))));
  43408. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  43409. 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)))));
  43410. };
  43411. return SIMDMatrix;
  43412. }());
  43413. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  43414. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  43415. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  43416. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  43417. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  43418. var SIMDHelper = (function () {
  43419. function SIMDHelper() {
  43420. }
  43421. Object.defineProperty(SIMDHelper, "IsEnabled", {
  43422. get: function () {
  43423. return SIMDHelper._isEnabled;
  43424. },
  43425. enumerable: true,
  43426. configurable: true
  43427. });
  43428. SIMDHelper.DisableSIMD = function () {
  43429. // Replace functions
  43430. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  43431. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  43432. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  43433. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  43434. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  43435. SIMDHelper._isEnabled = false;
  43436. };
  43437. SIMDHelper.EnableSIMD = function () {
  43438. if (self.SIMD === undefined) {
  43439. return;
  43440. }
  43441. // check if polyfills needed
  43442. if (!self.Math.fround) {
  43443. self.Math.fround = (function (array) { return function (x) {
  43444. return array[0] = x, array[0];
  43445. }; })(new Float32Array(1));
  43446. }
  43447. if (!self.Math.imul) {
  43448. self.Math.imul = function (a, b) {
  43449. var ah = (a >>> 16) & 0xffff;
  43450. var al = a & 0xffff;
  43451. var bh = (b >>> 16) & 0xffff;
  43452. var bl = b & 0xffff;
  43453. // the shift by 0 fixes the sign on the high part
  43454. // the final |0 converts the unsigned value into a signed value
  43455. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  43456. };
  43457. }
  43458. // Replace functions
  43459. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  43460. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  43461. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  43462. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  43463. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  43464. SIMDHelper._isEnabled = true;
  43465. };
  43466. return SIMDHelper;
  43467. }());
  43468. SIMDHelper._isEnabled = false;
  43469. BABYLON.SIMDHelper = SIMDHelper;
  43470. })(BABYLON || (BABYLON = {}));
  43471. //# sourceMappingURL=babylon.math.SIMD.js.map
  43472. var BABYLON;
  43473. (function (BABYLON) {
  43474. /**
  43475. * This class describe a rectangle that were added to the map.
  43476. * You have access to its coordinates either in pixel or normalized (UV)
  43477. */
  43478. var PackedRect = (function () {
  43479. function PackedRect(root, parent, pos, size) {
  43480. this._pos = pos;
  43481. this._size = size;
  43482. this._root = root;
  43483. this._parent = parent;
  43484. this._contentSize = null;
  43485. this._bottomNode = null;
  43486. this._leftNode = null;
  43487. this._initialSize = null;
  43488. this._rightNode = null;
  43489. }
  43490. Object.defineProperty(PackedRect.prototype, "pos", {
  43491. /**
  43492. * @returns the position of this node into the map
  43493. */
  43494. get: function () {
  43495. return this._pos;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. Object.defineProperty(PackedRect.prototype, "contentSize", {
  43501. /**
  43502. * @returns the size of the rectangle this node handles
  43503. */
  43504. get: function () {
  43505. return this._contentSize;
  43506. },
  43507. enumerable: true,
  43508. configurable: true
  43509. });
  43510. Object.defineProperty(PackedRect.prototype, "UVs", {
  43511. /**
  43512. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  43513. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  43514. */
  43515. get: function () {
  43516. return this.getUVsForCustomSize(this._root._size);
  43517. },
  43518. enumerable: true,
  43519. configurable: true
  43520. });
  43521. /**
  43522. * 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.
  43523. * This method will return the UVs for this part by given the custom size of what you really use
  43524. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  43525. */
  43526. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  43527. var mainWidth = this._root._size.width;
  43528. var mainHeight = this._root._size.height;
  43529. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  43530. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  43531. var uvs = new Array();
  43532. uvs.push(topLeft);
  43533. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  43534. uvs.push(rightBottom);
  43535. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  43536. return uvs;
  43537. };
  43538. /**
  43539. * Free this rectangle from the map.
  43540. * Call this method when you no longer need the rectangle to be in the map.
  43541. */
  43542. PackedRect.prototype.freeContent = function () {
  43543. if (!this.contentSize) {
  43544. return;
  43545. }
  43546. this._contentSize = null;
  43547. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  43548. this.attemptDefrag();
  43549. };
  43550. Object.defineProperty(PackedRect.prototype, "isUsed", {
  43551. get: function () {
  43552. return this._contentSize != null || this._leftNode != null;
  43553. },
  43554. enumerable: true,
  43555. configurable: true
  43556. });
  43557. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  43558. var node = this.findNode(contentSize);
  43559. // Not enough space...
  43560. if (!node) {
  43561. return null;
  43562. }
  43563. node.splitNode(contentSize);
  43564. return node;
  43565. };
  43566. PackedRect.prototype.findNode = function (size) {
  43567. var resNode = null;
  43568. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  43569. if (this.isUsed) {
  43570. if (this._leftNode) {
  43571. resNode = this._leftNode.findNode(size);
  43572. }
  43573. if (!resNode && this._rightNode) {
  43574. resNode = this._rightNode.findNode(size);
  43575. }
  43576. if (!resNode && this._bottomNode) {
  43577. resNode = this._bottomNode.findNode(size);
  43578. }
  43579. }
  43580. else if (this._initialSize) {
  43581. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  43582. resNode = this;
  43583. }
  43584. else {
  43585. return null;
  43586. }
  43587. }
  43588. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  43589. resNode = this;
  43590. }
  43591. return resNode;
  43592. };
  43593. PackedRect.prototype.splitNode = function (contentSize) {
  43594. // 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)
  43595. if (!this._contentSize && this._initialSize) {
  43596. this._contentSize = contentSize.clone();
  43597. 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));
  43598. return this._leftNode.splitNode(contentSize);
  43599. }
  43600. else {
  43601. this._contentSize = contentSize.clone();
  43602. this._initialSize = contentSize.clone();
  43603. if (contentSize.width !== this._size.width) {
  43604. 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));
  43605. }
  43606. if (contentSize.height !== this._size.height) {
  43607. 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));
  43608. }
  43609. return this;
  43610. }
  43611. };
  43612. PackedRect.prototype.attemptDefrag = function () {
  43613. if (!this.isUsed && this.isRecursiveFree) {
  43614. this.clearNode();
  43615. if (this._parent) {
  43616. this._parent.attemptDefrag();
  43617. }
  43618. }
  43619. };
  43620. PackedRect.prototype.clearNode = function () {
  43621. this._initialSize = null;
  43622. this._rightNode = null;
  43623. this._bottomNode = null;
  43624. };
  43625. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  43626. get: function () {
  43627. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  43628. },
  43629. enumerable: true,
  43630. configurable: true
  43631. });
  43632. PackedRect.prototype.evalFreeSize = function (size) {
  43633. var levelSize = 0;
  43634. if (!this.isUsed) {
  43635. if (this._initialSize) {
  43636. levelSize = this._initialSize.surface;
  43637. }
  43638. else {
  43639. levelSize = this._size.surface;
  43640. }
  43641. }
  43642. if (this._rightNode) {
  43643. levelSize += this._rightNode.evalFreeSize(0);
  43644. }
  43645. if (this._bottomNode) {
  43646. levelSize += this._bottomNode.evalFreeSize(0);
  43647. }
  43648. return levelSize + size;
  43649. };
  43650. return PackedRect;
  43651. }());
  43652. BABYLON.PackedRect = PackedRect;
  43653. /**
  43654. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  43655. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  43656. * 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.
  43657. */
  43658. var RectPackingMap = (function (_super) {
  43659. __extends(RectPackingMap, _super);
  43660. /**
  43661. * Create an instance of the object with a dimension using the given size
  43662. * @param size The dimension of the rectangle that will contain all the sub ones.
  43663. */
  43664. function RectPackingMap(size) {
  43665. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  43666. _this._root = _this;
  43667. return _this;
  43668. }
  43669. /**
  43670. * Add a rectangle, finding the best location to store it into the map
  43671. * @param size the dimension of the rectangle to store
  43672. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  43673. */
  43674. RectPackingMap.prototype.addRect = function (size) {
  43675. var node = this.findAndSplitNode(size);
  43676. return node;
  43677. };
  43678. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  43679. /**
  43680. * Return the current space free normalized between [0;1]
  43681. * @returns {}
  43682. */
  43683. get: function () {
  43684. var freeSize = 0;
  43685. freeSize = this.evalFreeSize(freeSize);
  43686. return freeSize / (this._size.width * this._size.height);
  43687. },
  43688. enumerable: true,
  43689. configurable: true
  43690. });
  43691. return RectPackingMap;
  43692. }(PackedRect));
  43693. BABYLON.RectPackingMap = RectPackingMap;
  43694. })(BABYLON || (BABYLON = {}));
  43695. //# sourceMappingURL=babylon.rectPackingMap.js.map
  43696. var BABYLON;
  43697. (function (BABYLON) {
  43698. var DynamicFloatArrayElementInfo = (function () {
  43699. function DynamicFloatArrayElementInfo() {
  43700. }
  43701. return DynamicFloatArrayElementInfo;
  43702. }());
  43703. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  43704. /**
  43705. * 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.
  43706. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  43707. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  43708. * 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.
  43709. * 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.
  43710. * 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".
  43711. */
  43712. var DynamicFloatArray = (function () {
  43713. /**
  43714. * Construct an instance of the dynamic float array
  43715. * @param stride size of one element in float (i.e. not bytes!)
  43716. * @param initialElementCount the number of available entries at construction
  43717. */
  43718. function DynamicFloatArray(stride, initialElementCount) {
  43719. this.compareValueOffset = null;
  43720. this.sortingAscending = true;
  43721. this._stride = stride;
  43722. this.buffer = new Float32Array(stride * initialElementCount);
  43723. this._lastUsed = 0;
  43724. this._firstFree = 0;
  43725. this._allEntries = new Array(initialElementCount);
  43726. this._freeEntries = new Array(initialElementCount);
  43727. for (var i = 0; i < initialElementCount; i++) {
  43728. var element = new DynamicFloatArrayElementInfo();
  43729. element.offset = i * stride;
  43730. this._allEntries[i] = element;
  43731. this._freeEntries[initialElementCount - i - 1] = element;
  43732. }
  43733. }
  43734. /**
  43735. * Allocate an element in the array.
  43736. * @return the element info instance that contains the offset into the main buffer of the element's location.
  43737. * Beware, this offset may change when you call pack()
  43738. */
  43739. DynamicFloatArray.prototype.allocElement = function () {
  43740. if (this._freeEntries.length === 0) {
  43741. this._growBuffer();
  43742. }
  43743. var el = this._freeEntries.pop();
  43744. this._lastUsed = Math.max(el.offset, this._lastUsed);
  43745. if (el.offset === this._firstFree) {
  43746. if (this._freeEntries.length > 0) {
  43747. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  43748. }
  43749. else {
  43750. this._firstFree += this._stride;
  43751. }
  43752. }
  43753. return el;
  43754. };
  43755. /**
  43756. * Free the element corresponding to the given element info
  43757. * @param elInfo the element that describe the allocated element
  43758. */
  43759. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43760. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43761. this._freeEntries.push(elInfo);
  43762. };
  43763. /**
  43764. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43765. * 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().
  43766. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43767. */
  43768. DynamicFloatArray.prototype.pack = function () {
  43769. // no free slot? no need to pack
  43770. if (this._freeEntries.length === 0) {
  43771. return this.buffer;
  43772. }
  43773. // If the buffer is already packed the last used will always be lower than the first free
  43774. // 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.
  43775. if (this._lastUsed < this._firstFree) {
  43776. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43777. return elementsBuffer_1;
  43778. }
  43779. var s = this._stride;
  43780. // 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
  43781. var lastFree = new DynamicFloatArrayElementInfo();
  43782. lastFree.offset = this.totalElementCount * s;
  43783. this._freeEntries.push(lastFree);
  43784. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43785. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43786. var firstFreeSlotOffset = sortedFree[0].offset;
  43787. var freeZoneSize = 1;
  43788. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43789. var prevOffset = sortedFree[0].offset;
  43790. for (var i = 1; i < sortedFree.length; i++) {
  43791. // 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
  43792. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43793. break;
  43794. }
  43795. var curFree = sortedFree[i];
  43796. var curOffset = curFree.offset;
  43797. // Compute the distance between this offset and the previous
  43798. var distance = curOffset - prevOffset;
  43799. // If the distance is the stride size, they are adjacent, it good, move to the next
  43800. if (distance === s) {
  43801. // Free zone is one element bigger
  43802. ++freeZoneSize;
  43803. // as we're about to iterate to the next, the cur becomes the previous...
  43804. prevOffset = curOffset;
  43805. continue;
  43806. }
  43807. // Distance is bigger, which means there's x element between the previous free and this one
  43808. var usedRange = (distance / s) - 1;
  43809. // Two cases the free zone is smaller than the data to move or bigger
  43810. // Copy what can fit in the free zone
  43811. var curMoveOffset = curOffset - s;
  43812. var copyCount = Math.min(freeZoneSize, usedRange);
  43813. for (var j = 0; j < copyCount; j++) {
  43814. var freeI = firstFreeSlotOffset / s;
  43815. var curI = curMoveOffset / s;
  43816. var moveEl = sortedAll[curI];
  43817. this._moveElement(moveEl, firstFreeSlotOffset);
  43818. var replacedEl = sortedAll[freeI];
  43819. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43820. replacedEl.offset = curMoveOffset;
  43821. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43822. sortedAll[freeI] = moveEl;
  43823. sortedAll[curI] = replacedEl;
  43824. curMoveOffset -= s;
  43825. firstFreeSlotOffset += s;
  43826. }
  43827. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43828. if (freeZoneSize <= usedRange) {
  43829. firstFreeSlotOffset = curMoveOffset + s;
  43830. freeZoneSize = 1 + copyCount;
  43831. }
  43832. else {
  43833. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43834. }
  43835. // as we're about to iterate to the next, the cur becomes the previous...
  43836. prevOffset = curOffset;
  43837. }
  43838. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43839. this._lastUsed = firstFreeSlotOffset - s;
  43840. this._firstFree = firstFreeSlotOffset;
  43841. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43842. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43843. this._allEntries = sortedAll;
  43844. return elementsBuffer;
  43845. };
  43846. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43847. for (var i = 0; i < this._stride; i++) {
  43848. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43849. }
  43850. element.offset = destOffset;
  43851. };
  43852. DynamicFloatArray.prototype._growBuffer = function () {
  43853. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43854. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43855. var newBuffer = new Float32Array(newElCount * this._stride);
  43856. newBuffer.set(this.buffer);
  43857. var curCount = this.totalElementCount;
  43858. var addedCount = newElCount - this.totalElementCount;
  43859. for (var i = 0; i < addedCount; i++) {
  43860. var element = new DynamicFloatArrayElementInfo();
  43861. element.offset = (curCount + i) * this.stride;
  43862. this._allEntries.push(element);
  43863. this._freeEntries[addedCount - i - 1] = element;
  43864. }
  43865. this._firstFree = curCount * this.stride;
  43866. this.buffer = newBuffer;
  43867. };
  43868. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43869. /**
  43870. * Get the total count of entries that can fit in the current buffer
  43871. * @returns the elements count
  43872. */
  43873. get: function () {
  43874. return this._allEntries.length;
  43875. },
  43876. enumerable: true,
  43877. configurable: true
  43878. });
  43879. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43880. /**
  43881. * Get the count of free entries that can still be allocated without resizing the buffer
  43882. * @returns the free elements count
  43883. */
  43884. get: function () {
  43885. return this._freeEntries.length;
  43886. },
  43887. enumerable: true,
  43888. configurable: true
  43889. });
  43890. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43891. /**
  43892. * Get the count of allocated elements
  43893. * @returns the allocated elements count
  43894. */
  43895. get: function () {
  43896. return this._allEntries.length - this._freeEntries.length;
  43897. },
  43898. enumerable: true,
  43899. configurable: true
  43900. });
  43901. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43902. /**
  43903. * Return the size of one element in float
  43904. * @returns the size in float
  43905. */
  43906. get: function () {
  43907. return this._stride;
  43908. },
  43909. enumerable: true,
  43910. configurable: true
  43911. });
  43912. DynamicFloatArray.prototype.sort = function () {
  43913. var _this = this;
  43914. if (!this.compareValueOffset) {
  43915. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43916. }
  43917. var count = this.usedElementCount;
  43918. // Do we have to (re)create the sort table?
  43919. if (!this._sortTable || this._sortTable.length < count) {
  43920. // 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...
  43921. var newCount = Math.min(this.totalElementCount, count * 2);
  43922. this._sortTable = new Array(newCount);
  43923. }
  43924. if (!this._sortedTable || this._sortedTable.length !== count) {
  43925. this._sortedTable = new Array(count);
  43926. }
  43927. // Because, you know...
  43928. this.pack();
  43929. //let stride = this.stride;
  43930. //for (let i = 0; i < count; i++) {
  43931. // let si = this._sortTable[i];
  43932. // if (!si) {
  43933. // si = new SortInfo();
  43934. // this._sortTable[i] = si;
  43935. // }
  43936. // si.entry = this._allEntries[i];
  43937. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43938. // si.swapedOffset = null;
  43939. // this._sortedTable[i] = si;
  43940. //}
  43941. var curOffset = 0;
  43942. var stride = this.stride;
  43943. for (var i = 0; i < count; i++, curOffset += stride) {
  43944. var si = this._sortTable[i];
  43945. if (!si) {
  43946. si = new SortInfo();
  43947. this._sortTable[i] = si;
  43948. }
  43949. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43950. si.offset = curOffset;
  43951. si.swapedOffset = null;
  43952. this._sortedTable[i] = si;
  43953. }
  43954. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43955. if (this.sortingAscending) {
  43956. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43957. }
  43958. else {
  43959. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43960. }
  43961. var swapElements = function (src, dst) {
  43962. for (var i = 0; i < stride; i++) {
  43963. var tps = _this.buffer[dst + i];
  43964. _this.buffer[dst + i] = _this.buffer[src + i];
  43965. _this.buffer[src + i] = tps;
  43966. }
  43967. };
  43968. // 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:
  43969. // 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),
  43970. // and I still want something with a good algorithm complexity.
  43971. // 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,
  43972. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43973. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43974. // 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
  43975. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43976. // 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
  43977. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43978. for (var i = 0; i < count; i++) {
  43979. // Get the element to move
  43980. var sourceSI = this._sortedTable[i];
  43981. var destSI = this._sortTable[i];
  43982. var sourceOff = sourceSI.offset;
  43983. // If the source changed location, find the new one
  43984. if (sourceSI.swapedOffset) {
  43985. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43986. var curSI = sourceSI;
  43987. while (curSI.swapedOffset) {
  43988. curSI = this._sortTable[curSI.swapedOffset / stride];
  43989. }
  43990. // Finally get the right location
  43991. sourceOff = curSI.offset;
  43992. }
  43993. // Tag the element being replaced with its new location
  43994. destSI.swapedOffset = sourceOff;
  43995. // Swap elements (only if needed)
  43996. if (sourceOff !== destSI.offset) {
  43997. swapElements(sourceOff, destSI.offset);
  43998. }
  43999. // Update the offset in the corresponding DFAE
  44000. //sourceSI.entry.offset = destSI.entry.offset;
  44001. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  44002. }
  44003. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44004. return true;
  44005. };
  44006. return DynamicFloatArray;
  44007. }());
  44008. BABYLON.DynamicFloatArray = DynamicFloatArray;
  44009. var SortInfo = (function () {
  44010. function SortInfo() {
  44011. this.compareData = this.offset = this.swapedOffset = null;
  44012. }
  44013. return SortInfo;
  44014. }());
  44015. })(BABYLON || (BABYLON = {}));
  44016. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  44017. var BABYLON;
  44018. (function (BABYLON) {
  44019. var MapTexture = (function (_super) {
  44020. __extends(MapTexture, _super);
  44021. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  44022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44023. if (useMipMap === void 0) { useMipMap = false; }
  44024. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  44025. _this.name = name;
  44026. _this._size = size;
  44027. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44028. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44029. // Create the rectPackMap that will allocate portion of the texture
  44030. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  44031. // Create the texture that will store the content
  44032. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  44033. return _this;
  44034. }
  44035. /**
  44036. * Allocate a rectangle of a given size in the texture map
  44037. * @param size the size of the rectangle to allocation
  44038. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  44039. */
  44040. MapTexture.prototype.allocateRect = function (size) {
  44041. return this._rectPackingMap.addRect(size);
  44042. };
  44043. /**
  44044. * Free a given rectangle from the texture map
  44045. * @param rectInfo the instance corresponding to the rect to free.
  44046. */
  44047. MapTexture.prototype.freeRect = function (rectInfo) {
  44048. if (rectInfo) {
  44049. rectInfo.freeContent();
  44050. }
  44051. };
  44052. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  44053. /**
  44054. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  44055. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  44056. * @returns {}
  44057. */
  44058. get: function () {
  44059. return this._rectPackingMap.freeSpace;
  44060. },
  44061. enumerable: true,
  44062. configurable: true
  44063. });
  44064. /**
  44065. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  44066. * 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.
  44067. * Don't forget to call unbindTexture when you're done rendering
  44068. * @param rect the zone to render to
  44069. * @param clear true to clear the portion's color/depth data
  44070. */
  44071. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  44072. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  44073. };
  44074. /**
  44075. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  44076. * 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.
  44077. * Don't forget to call unbindTexture when you're done rendering
  44078. * @param pos the position into the texture
  44079. * @param size the portion to fit the clip space to
  44080. * @param clear true to clear the portion's color/depth data
  44081. */
  44082. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  44083. var engine = this.getScene().getEngine();
  44084. engine.bindFramebuffer(this._texture);
  44085. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  44086. if (clear) {
  44087. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  44088. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  44089. }
  44090. };
  44091. /**
  44092. * Unbind the texture map from the rendering engine.
  44093. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  44094. * @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.
  44095. */
  44096. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  44097. // Dump ?
  44098. if (dumpForDebug) {
  44099. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  44100. }
  44101. var engine = this.getScene().getEngine();
  44102. if (this._replacedViewport) {
  44103. engine.setViewport(this._replacedViewport);
  44104. this._replacedViewport = null;
  44105. }
  44106. engine.unBindFramebuffer(this._texture);
  44107. };
  44108. Object.defineProperty(MapTexture.prototype, "canRescale", {
  44109. get: function () {
  44110. return false;
  44111. },
  44112. enumerable: true,
  44113. configurable: true
  44114. });
  44115. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  44116. // Anyway, there's not much point to use this method for this kind of texture I guess
  44117. MapTexture.prototype.clone = function () {
  44118. return null;
  44119. };
  44120. return MapTexture;
  44121. }(BABYLON.Texture));
  44122. BABYLON.MapTexture = MapTexture;
  44123. })(BABYLON || (BABYLON = {}));
  44124. //# sourceMappingURL=babylon.mapTexture.js.map
  44125. var BABYLON;
  44126. (function (BABYLON) {
  44127. var ShaderMaterial = (function (_super) {
  44128. __extends(ShaderMaterial, _super);
  44129. function ShaderMaterial(name, scene, shaderPath, options) {
  44130. var _this = _super.call(this, name, scene) || this;
  44131. _this._textures = {};
  44132. _this._textureArrays = {};
  44133. _this._floats = {};
  44134. _this._floatsArrays = {};
  44135. _this._colors3 = {};
  44136. _this._colors4 = {};
  44137. _this._vectors2 = {};
  44138. _this._vectors3 = {};
  44139. _this._vectors4 = {};
  44140. _this._matrices = {};
  44141. _this._matrices3x3 = {};
  44142. _this._matrices2x2 = {};
  44143. _this._vectors3Arrays = {};
  44144. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44145. _this._shaderPath = shaderPath;
  44146. options.needAlphaBlending = options.needAlphaBlending || false;
  44147. options.needAlphaTesting = options.needAlphaTesting || false;
  44148. options.attributes = options.attributes || ["position", "normal", "uv"];
  44149. options.uniforms = options.uniforms || ["worldViewProjection"];
  44150. options.samplers = options.samplers || [];
  44151. options.defines = options.defines || [];
  44152. _this._options = options;
  44153. return _this;
  44154. }
  44155. ShaderMaterial.prototype.getClassName = function () {
  44156. return "ShaderMaterial";
  44157. };
  44158. ShaderMaterial.prototype.needAlphaBlending = function () {
  44159. return this._options.needAlphaBlending;
  44160. };
  44161. ShaderMaterial.prototype.needAlphaTesting = function () {
  44162. return this._options.needAlphaTesting;
  44163. };
  44164. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44165. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44166. this._options.uniforms.push(uniformName);
  44167. }
  44168. };
  44169. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44170. if (this._options.samplers.indexOf(name) === -1) {
  44171. this._options.samplers.push(name);
  44172. }
  44173. this._textures[name] = texture;
  44174. return this;
  44175. };
  44176. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44177. if (this._options.samplers.indexOf(name) === -1) {
  44178. this._options.samplers.push(name);
  44179. }
  44180. this._checkUniform(name);
  44181. this._textureArrays[name] = textures;
  44182. return this;
  44183. };
  44184. ShaderMaterial.prototype.setFloat = function (name, value) {
  44185. this._checkUniform(name);
  44186. this._floats[name] = value;
  44187. return this;
  44188. };
  44189. ShaderMaterial.prototype.setFloats = function (name, value) {
  44190. this._checkUniform(name);
  44191. this._floatsArrays[name] = value;
  44192. return this;
  44193. };
  44194. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44195. this._checkUniform(name);
  44196. this._colors3[name] = value;
  44197. return this;
  44198. };
  44199. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44200. this._checkUniform(name);
  44201. this._colors4[name] = value;
  44202. return this;
  44203. };
  44204. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44205. this._checkUniform(name);
  44206. this._vectors2[name] = value;
  44207. return this;
  44208. };
  44209. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44210. this._checkUniform(name);
  44211. this._vectors3[name] = value;
  44212. return this;
  44213. };
  44214. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44215. this._checkUniform(name);
  44216. this._vectors4[name] = value;
  44217. return this;
  44218. };
  44219. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44220. this._checkUniform(name);
  44221. this._matrices[name] = value;
  44222. return this;
  44223. };
  44224. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44225. this._checkUniform(name);
  44226. this._matrices3x3[name] = value;
  44227. return this;
  44228. };
  44229. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  44230. this._checkUniform(name);
  44231. this._matrices2x2[name] = value;
  44232. return this;
  44233. };
  44234. ShaderMaterial.prototype.setArray3 = function (name, value) {
  44235. this._checkUniform(name);
  44236. this._vectors3Arrays[name] = value;
  44237. return this;
  44238. };
  44239. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44240. if (!mesh) {
  44241. return true;
  44242. }
  44243. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  44244. return false;
  44245. }
  44246. return false;
  44247. };
  44248. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  44249. var scene = this.getScene();
  44250. var engine = scene.getEngine();
  44251. if (!this.checkReadyOnEveryCall) {
  44252. if (this._renderId === scene.getRenderId()) {
  44253. if (this._checkCache(scene, mesh, useInstances)) {
  44254. return true;
  44255. }
  44256. }
  44257. }
  44258. // Instances
  44259. var defines = [];
  44260. var fallbacks = new BABYLON.EffectFallbacks();
  44261. if (useInstances) {
  44262. defines.push("#define INSTANCES");
  44263. }
  44264. for (var index = 0; index < this._options.defines.length; index++) {
  44265. defines.push(this._options.defines[index]);
  44266. }
  44267. // Bones
  44268. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  44269. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44270. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44271. fallbacks.addCPUSkinningFallback(0, mesh);
  44272. }
  44273. // Alpha test
  44274. if (engine.getAlphaTesting()) {
  44275. defines.push("#define ALPHATEST");
  44276. }
  44277. var previousEffect = this._effect;
  44278. var join = defines.join("\n");
  44279. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  44280. if (!this._effect.isReady()) {
  44281. return false;
  44282. }
  44283. if (previousEffect !== this._effect) {
  44284. scene.resetCachedMaterial();
  44285. }
  44286. this._renderId = scene.getRenderId();
  44287. return true;
  44288. };
  44289. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44290. var scene = this.getScene();
  44291. if (this._options.uniforms.indexOf("world") !== -1) {
  44292. this._effect.setMatrix("world", world);
  44293. }
  44294. if (this._options.uniforms.indexOf("worldView") !== -1) {
  44295. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  44296. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  44297. }
  44298. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  44299. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  44300. }
  44301. };
  44302. ShaderMaterial.prototype.bind = function (world, mesh) {
  44303. // Std values
  44304. this.bindOnlyWorldMatrix(world);
  44305. if (this.getScene().getCachedMaterial() !== this) {
  44306. if (this._options.uniforms.indexOf("view") !== -1) {
  44307. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  44308. }
  44309. if (this._options.uniforms.indexOf("projection") !== -1) {
  44310. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  44311. }
  44312. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  44313. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  44314. }
  44315. // Bones
  44316. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44317. var name;
  44318. // Texture
  44319. for (name in this._textures) {
  44320. this._effect.setTexture(name, this._textures[name]);
  44321. }
  44322. // Texture arrays
  44323. for (name in this._textureArrays) {
  44324. this._effect.setTextureArray(name, this._textureArrays[name]);
  44325. }
  44326. // Float
  44327. for (name in this._floats) {
  44328. this._effect.setFloat(name, this._floats[name]);
  44329. }
  44330. // Float s
  44331. for (name in this._floatsArrays) {
  44332. this._effect.setArray(name, this._floatsArrays[name]);
  44333. }
  44334. // Color3
  44335. for (name in this._colors3) {
  44336. this._effect.setColor3(name, this._colors3[name]);
  44337. }
  44338. // Color4
  44339. for (name in this._colors4) {
  44340. var color = this._colors4[name];
  44341. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  44342. }
  44343. // Vector2
  44344. for (name in this._vectors2) {
  44345. this._effect.setVector2(name, this._vectors2[name]);
  44346. }
  44347. // Vector3
  44348. for (name in this._vectors3) {
  44349. this._effect.setVector3(name, this._vectors3[name]);
  44350. }
  44351. // Vector4
  44352. for (name in this._vectors4) {
  44353. this._effect.setVector4(name, this._vectors4[name]);
  44354. }
  44355. // Matrix
  44356. for (name in this._matrices) {
  44357. this._effect.setMatrix(name, this._matrices[name]);
  44358. }
  44359. // Matrix 3x3
  44360. for (name in this._matrices3x3) {
  44361. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  44362. }
  44363. // Matrix 2x2
  44364. for (name in this._matrices2x2) {
  44365. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  44366. }
  44367. // Vector3Array
  44368. for (name in this._vectors3Arrays) {
  44369. this._effect.setArray3(name, this._vectors3Arrays[name]);
  44370. }
  44371. }
  44372. _super.prototype.bind.call(this, world, mesh);
  44373. };
  44374. ShaderMaterial.prototype.clone = function (name) {
  44375. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  44376. return newShaderMaterial;
  44377. };
  44378. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44379. if (forceDisposeTextures) {
  44380. var name;
  44381. for (name in this._textures) {
  44382. this._textures[name].dispose();
  44383. }
  44384. for (name in this._textureArrays) {
  44385. var array = this._textureArrays[name];
  44386. for (var index = 0; index < array.length; index++) {
  44387. array[index].dispose();
  44388. }
  44389. }
  44390. }
  44391. this._textures = {};
  44392. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44393. };
  44394. ShaderMaterial.prototype.serialize = function () {
  44395. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44396. serializationObject.customType = "BABYLON.ShaderMaterial";
  44397. serializationObject.options = this._options;
  44398. serializationObject.shaderPath = this._shaderPath;
  44399. var name;
  44400. // Texture
  44401. serializationObject.textures = {};
  44402. for (name in this._textures) {
  44403. serializationObject.textures[name] = this._textures[name].serialize();
  44404. }
  44405. // Texture arrays
  44406. serializationObject.textureArrays = {};
  44407. for (name in this._textureArrays) {
  44408. serializationObject.textureArrays[name] = [];
  44409. var array = this._textureArrays[name];
  44410. for (var index = 0; index < array.length; index++) {
  44411. serializationObject.textureArrays[name].push(array[index].serialize());
  44412. }
  44413. }
  44414. // Float
  44415. serializationObject.floats = {};
  44416. for (name in this._floats) {
  44417. serializationObject.floats[name] = this._floats[name];
  44418. }
  44419. // Float s
  44420. serializationObject.floatArrays = {};
  44421. for (name in this._floatsArrays) {
  44422. serializationObject.floatArrays[name] = this._floatsArrays[name];
  44423. }
  44424. // Color3
  44425. serializationObject.colors3 = {};
  44426. for (name in this._colors3) {
  44427. serializationObject.colors3[name] = this._colors3[name].asArray();
  44428. }
  44429. // Color4
  44430. serializationObject.colors4 = {};
  44431. for (name in this._colors4) {
  44432. serializationObject.colors4[name] = this._colors4[name].asArray();
  44433. }
  44434. // Vector2
  44435. serializationObject.vectors2 = {};
  44436. for (name in this._vectors2) {
  44437. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  44438. }
  44439. // Vector3
  44440. serializationObject.vectors3 = {};
  44441. for (name in this._vectors3) {
  44442. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  44443. }
  44444. // Vector4
  44445. serializationObject.vectors4 = {};
  44446. for (name in this._vectors4) {
  44447. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  44448. }
  44449. // Matrix
  44450. serializationObject.matrices = {};
  44451. for (name in this._matrices) {
  44452. serializationObject.matrices[name] = this._matrices[name].asArray();
  44453. }
  44454. // Matrix 3x3
  44455. serializationObject.matrices3x3 = {};
  44456. for (name in this._matrices3x3) {
  44457. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  44458. }
  44459. // Matrix 2x2
  44460. serializationObject.matrices2x2 = {};
  44461. for (name in this._matrices2x2) {
  44462. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  44463. }
  44464. // Vector3Array
  44465. serializationObject.vectors3Arrays = {};
  44466. for (name in this._vectors3Arrays) {
  44467. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  44468. }
  44469. return serializationObject;
  44470. };
  44471. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  44472. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  44473. var name;
  44474. // Texture
  44475. for (name in source.textures) {
  44476. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  44477. }
  44478. // Texture arrays
  44479. for (name in source.textureArrays) {
  44480. var array = source.textureArrays[name];
  44481. var textureArray = new Array();
  44482. for (var index = 0; index < array.length; index++) {
  44483. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  44484. }
  44485. material.setTextureArray(name, textureArray);
  44486. }
  44487. // Float
  44488. for (name in source.floats) {
  44489. material.setFloat(name, source.floats[name]);
  44490. }
  44491. // Float s
  44492. for (name in source.floatsArrays) {
  44493. material.setFloats(name, source.floatsArrays[name]);
  44494. }
  44495. // Color3
  44496. for (name in source.colors3) {
  44497. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  44498. }
  44499. // Color4
  44500. for (name in source.colors4) {
  44501. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  44502. }
  44503. // Vector2
  44504. for (name in source.vectors2) {
  44505. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  44506. }
  44507. // Vector3
  44508. for (name in source.vectors3) {
  44509. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  44510. }
  44511. // Vector4
  44512. for (name in source.vectors4) {
  44513. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  44514. }
  44515. // Matrix
  44516. for (name in source.matrices) {
  44517. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  44518. }
  44519. // Matrix 3x3
  44520. for (name in source.matrices3x3) {
  44521. material.setMatrix3x3(name, source.matrices3x3[name]);
  44522. }
  44523. // Matrix 2x2
  44524. for (name in source.matrices2x2) {
  44525. material.setMatrix2x2(name, source.matrices2x2[name]);
  44526. }
  44527. // Vector3Array
  44528. for (name in source.vectors3Arrays) {
  44529. material.setArray3(name, source.vectors3Arrays[name]);
  44530. }
  44531. return material;
  44532. };
  44533. return ShaderMaterial;
  44534. }(BABYLON.Material));
  44535. BABYLON.ShaderMaterial = ShaderMaterial;
  44536. })(BABYLON || (BABYLON = {}));
  44537. //# sourceMappingURL=babylon.shaderMaterial.js.map
  44538. var BABYLON;
  44539. (function (BABYLON) {
  44540. var Internals;
  44541. (function (Internals) {
  44542. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  44543. // All values and structures referenced from:
  44544. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  44545. var DDS_MAGIC = 0x20534444;
  44546. 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;
  44547. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  44548. 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;
  44549. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  44550. function FourCCToInt32(value) {
  44551. return value.charCodeAt(0) +
  44552. (value.charCodeAt(1) << 8) +
  44553. (value.charCodeAt(2) << 16) +
  44554. (value.charCodeAt(3) << 24);
  44555. }
  44556. function Int32ToFourCC(value) {
  44557. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  44558. }
  44559. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  44560. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  44561. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  44562. var headerLengthInt = 31; // The header length in 32 bit ints
  44563. // Offsets into the header array
  44564. var off_magic = 0;
  44565. var off_size = 1;
  44566. var off_flags = 2;
  44567. var off_height = 3;
  44568. var off_width = 4;
  44569. var off_mipmapCount = 7;
  44570. var off_pfFlags = 20;
  44571. var off_pfFourCC = 21;
  44572. var off_RGBbpp = 22;
  44573. var off_RMask = 23;
  44574. var off_GMask = 24;
  44575. var off_BMask = 25;
  44576. var off_AMask = 26;
  44577. var off_caps1 = 27;
  44578. var off_caps2 = 28;
  44579. ;
  44580. var DDSTools = (function () {
  44581. function DDSTools() {
  44582. }
  44583. DDSTools.GetDDSInfo = function (arrayBuffer) {
  44584. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  44585. var mipmapCount = 1;
  44586. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  44587. mipmapCount = Math.max(1, header[off_mipmapCount]);
  44588. }
  44589. return {
  44590. width: header[off_width],
  44591. height: header[off_height],
  44592. mipmapCount: mipmapCount,
  44593. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  44594. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  44595. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  44596. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  44597. };
  44598. };
  44599. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  44600. var byteArray = new Uint8Array(dataLength);
  44601. var srcData = new Uint8Array(arrayBuffer);
  44602. var index = 0;
  44603. for (var y = height - 1; y >= 0; y--) {
  44604. for (var x = 0; x < width; x++) {
  44605. var srcPos = dataOffset + (x + y * width) * 4;
  44606. byteArray[index + 2] = srcData[srcPos];
  44607. byteArray[index + 1] = srcData[srcPos + 1];
  44608. byteArray[index] = srcData[srcPos + 2];
  44609. byteArray[index + 3] = srcData[srcPos + 3];
  44610. index += 4;
  44611. }
  44612. }
  44613. return byteArray;
  44614. };
  44615. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  44616. var byteArray = new Uint8Array(dataLength);
  44617. var srcData = new Uint8Array(arrayBuffer);
  44618. var index = 0;
  44619. for (var y = height - 1; y >= 0; y--) {
  44620. for (var x = 0; x < width; x++) {
  44621. var srcPos = dataOffset + (x + y * width) * 3;
  44622. byteArray[index + 2] = srcData[srcPos];
  44623. byteArray[index + 1] = srcData[srcPos + 1];
  44624. byteArray[index] = srcData[srcPos + 2];
  44625. index += 3;
  44626. }
  44627. }
  44628. return byteArray;
  44629. };
  44630. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  44631. var byteArray = new Uint8Array(dataLength);
  44632. var srcData = new Uint8Array(arrayBuffer);
  44633. var index = 0;
  44634. for (var y = height - 1; y >= 0; y--) {
  44635. for (var x = 0; x < width; x++) {
  44636. var srcPos = dataOffset + (x + y * width);
  44637. byteArray[index] = srcData[srcPos];
  44638. index++;
  44639. }
  44640. }
  44641. return byteArray;
  44642. };
  44643. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  44644. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  44645. if (header[off_magic] != DDS_MAGIC) {
  44646. BABYLON.Tools.Error("Invalid magic number in DDS header");
  44647. return;
  44648. }
  44649. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  44650. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  44651. return;
  44652. }
  44653. if (info.isFourCC) {
  44654. fourCC = header[off_pfFourCC];
  44655. switch (fourCC) {
  44656. case FOURCC_DXT1:
  44657. blockBytes = 8;
  44658. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  44659. break;
  44660. case FOURCC_DXT3:
  44661. blockBytes = 16;
  44662. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  44663. break;
  44664. case FOURCC_DXT5:
  44665. blockBytes = 16;
  44666. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  44667. break;
  44668. default:
  44669. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  44670. return;
  44671. }
  44672. }
  44673. mipmapCount = 1;
  44674. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  44675. mipmapCount = Math.max(1, header[off_mipmapCount]);
  44676. }
  44677. var bpp = header[off_RGBbpp];
  44678. for (var face = 0; face < faces; face++) {
  44679. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  44680. width = header[off_width];
  44681. height = header[off_height];
  44682. dataOffset = header[off_size] + 4;
  44683. for (i = 0; i < mipmapCount; ++i) {
  44684. if (info.isRGB) {
  44685. if (bpp === 24) {
  44686. dataLength = width * height * 3;
  44687. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44688. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  44689. }
  44690. else {
  44691. dataLength = width * height * 4;
  44692. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44693. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  44694. }
  44695. }
  44696. else if (info.isLuminance) {
  44697. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  44698. var unpaddedRowSize = width;
  44699. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  44700. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  44701. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  44702. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  44703. }
  44704. else {
  44705. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  44706. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  44707. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  44708. }
  44709. dataOffset += dataLength;
  44710. width *= 0.5;
  44711. height *= 0.5;
  44712. width = Math.max(1.0, width);
  44713. height = Math.max(1.0, height);
  44714. }
  44715. }
  44716. };
  44717. return DDSTools;
  44718. }());
  44719. Internals.DDSTools = DDSTools;
  44720. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44721. })(BABYLON || (BABYLON = {}));
  44722. //# sourceMappingURL=babylon.tools.dds.js.map
  44723. var BABYLON;
  44724. (function (BABYLON) {
  44725. var Internals;
  44726. (function (Internals) {
  44727. /**
  44728. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  44729. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  44730. */
  44731. var KhronosTextureContainer = (function () {
  44732. /**
  44733. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  44734. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  44735. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  44736. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  44737. */
  44738. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  44739. this.arrayBuffer = arrayBuffer;
  44740. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  44741. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  44742. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  44743. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  44744. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  44745. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  44746. BABYLON.Tools.Error("texture missing KTX identifier");
  44747. return;
  44748. }
  44749. // load the reset of the header in native 32 bit int
  44750. var header = new Int32Array(this.arrayBuffer, 12, 13);
  44751. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  44752. var oppositeEndianess = header[0] === 0x01020304;
  44753. // read all the header elements in order they exist in the file, without modification (sans endainness)
  44754. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  44755. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  44756. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  44757. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  44758. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  44759. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  44760. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  44761. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  44762. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  44763. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  44764. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  44765. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  44766. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  44767. if (this.glType !== 0) {
  44768. BABYLON.Tools.Error("only compressed formats currently supported");
  44769. return;
  44770. }
  44771. else {
  44772. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  44773. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  44774. }
  44775. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  44776. BABYLON.Tools.Error("only 2D textures currently supported");
  44777. return;
  44778. }
  44779. if (this.numberOfArrayElements !== 0) {
  44780. BABYLON.Tools.Error("texture arrays not currently supported");
  44781. return;
  44782. }
  44783. if (this.numberOfFaces !== facesExpected) {
  44784. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  44785. return;
  44786. }
  44787. // we now have a completely validated file, so could use existence of loadType as success
  44788. // would need to make this more elaborate & adjust checks above to support more than one load type
  44789. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  44790. }
  44791. // not as fast hardware based, but will probably never need to use
  44792. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  44793. return ((val & 0xFF) << 24)
  44794. | ((val & 0xFF00) << 8)
  44795. | ((val >> 8) & 0xFF00)
  44796. | ((val >> 24) & 0xFF);
  44797. };
  44798. /**
  44799. * It is assumed that the texture has already been created & is currently bound
  44800. */
  44801. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  44802. switch (this.loadType) {
  44803. case KhronosTextureContainer.COMPRESSED_2D:
  44804. this._upload2DCompressedLevels(gl, loadMipmaps);
  44805. break;
  44806. case KhronosTextureContainer.TEX_2D:
  44807. case KhronosTextureContainer.COMPRESSED_3D:
  44808. case KhronosTextureContainer.TEX_3D:
  44809. }
  44810. };
  44811. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  44812. // initialize width & height for level 1
  44813. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  44814. var width = this.pixelWidth;
  44815. var height = this.pixelHeight;
  44816. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  44817. for (var level = 0; level < mipmapCount; level++) {
  44818. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  44819. for (var face = 0; face < this.numberOfFaces; face++) {
  44820. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  44821. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  44822. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  44823. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  44824. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  44825. }
  44826. width = Math.max(1.0, width * 0.5);
  44827. height = Math.max(1.0, height * 0.5);
  44828. }
  44829. };
  44830. return KhronosTextureContainer;
  44831. }());
  44832. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  44833. // load types
  44834. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  44835. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  44836. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  44837. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  44838. Internals.KhronosTextureContainer = KhronosTextureContainer;
  44839. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44840. })(BABYLON || (BABYLON = {}));
  44841. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  44842. var BABYLON;
  44843. (function (BABYLON) {
  44844. var CannonJSPlugin = (function () {
  44845. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  44846. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  44847. if (iterations === void 0) { iterations = 10; }
  44848. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  44849. this.name = "CannonJSPlugin";
  44850. this._physicsMaterials = [];
  44851. this._fixedTimeStep = 1 / 60;
  44852. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44853. this._currentCollisionGroup = 2;
  44854. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  44855. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  44856. this._tmpPosition = BABYLON.Vector3.Zero();
  44857. this._tmpQuaternion = new BABYLON.Quaternion();
  44858. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  44859. this._tmpDeltaRotation = new BABYLON.Quaternion();
  44860. this._tmpUnityRotation = new BABYLON.Quaternion();
  44861. if (!this.isSupported()) {
  44862. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  44863. return;
  44864. }
  44865. this.world = new CANNON.World();
  44866. this.world.broadphase = new CANNON.NaiveBroadphase();
  44867. this.world.solver.iterations = iterations;
  44868. }
  44869. CannonJSPlugin.prototype.setGravity = function (gravity) {
  44870. this.world.gravity.copy(gravity);
  44871. };
  44872. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  44873. this._fixedTimeStep = timeStep;
  44874. };
  44875. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  44876. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  44877. };
  44878. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  44879. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44880. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44881. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  44882. };
  44883. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  44884. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  44885. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  44886. impostor.physicsBody.applyForce(impulse, worldPoint);
  44887. };
  44888. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  44889. //parent-child relationship. Does this impostor has a parent impostor?
  44890. if (impostor.parent) {
  44891. if (impostor.physicsBody) {
  44892. this.removePhysicsBody(impostor);
  44893. //TODO is that needed?
  44894. impostor.forceUpdate();
  44895. }
  44896. return;
  44897. }
  44898. //should a new body be created for this impostor?
  44899. if (impostor.isBodyInitRequired()) {
  44900. var shape = this._createShape(impostor);
  44901. //unregister events, if body is being changed
  44902. var oldBody = impostor.physicsBody;
  44903. if (oldBody) {
  44904. this.removePhysicsBody(impostor);
  44905. }
  44906. //create the body and material
  44907. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  44908. var bodyCreationObject = {
  44909. mass: impostor.getParam("mass"),
  44910. material: material
  44911. };
  44912. // A simple extend, in case native options were used.
  44913. var nativeOptions = impostor.getParam("nativeOptions");
  44914. for (var key in nativeOptions) {
  44915. if (nativeOptions.hasOwnProperty(key)) {
  44916. bodyCreationObject[key] = nativeOptions[key];
  44917. }
  44918. }
  44919. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  44920. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  44921. this.world.addEventListener("preStep", impostor.beforeStep);
  44922. this.world.addEventListener("postStep", impostor.afterStep);
  44923. impostor.physicsBody.addShape(shape);
  44924. this.world.add(impostor.physicsBody);
  44925. //try to keep the body moving in the right direction by taking old properties.
  44926. //Should be tested!
  44927. if (oldBody) {
  44928. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  44929. impostor.physicsBody[param].copy(oldBody[param]);
  44930. });
  44931. }
  44932. this._processChildMeshes(impostor);
  44933. }
  44934. //now update the body's transformation
  44935. this._updatePhysicsBodyTransformation(impostor);
  44936. };
  44937. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  44938. var _this = this;
  44939. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  44940. if (meshChildren.length) {
  44941. var processMesh = function (localPosition, mesh) {
  44942. var childImpostor = mesh.getPhysicsImpostor();
  44943. if (childImpostor) {
  44944. var parent = childImpostor.parent;
  44945. if (parent !== mainImpostor) {
  44946. var localPosition = mesh.position;
  44947. if (childImpostor.physicsBody) {
  44948. _this.removePhysicsBody(childImpostor);
  44949. childImpostor.physicsBody = null;
  44950. }
  44951. childImpostor.parent = mainImpostor;
  44952. childImpostor.resetUpdateFlags();
  44953. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  44954. //Add the mass of the children.
  44955. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  44956. }
  44957. }
  44958. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  44959. };
  44960. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  44961. }
  44962. };
  44963. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  44964. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  44965. this.world.removeEventListener("preStep", impostor.beforeStep);
  44966. this.world.removeEventListener("postStep", impostor.afterStep);
  44967. this.world.remove(impostor.physicsBody);
  44968. };
  44969. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  44970. var mainBody = impostorJoint.mainImpostor.physicsBody;
  44971. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  44972. if (!mainBody || !connectedBody) {
  44973. return;
  44974. }
  44975. var constraint;
  44976. var jointData = impostorJoint.joint.jointData;
  44977. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  44978. var constraintData = {
  44979. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  44980. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  44981. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  44982. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  44983. maxForce: jointData.nativeParams.maxForce,
  44984. collideConnected: !!jointData.collision
  44985. };
  44986. switch (impostorJoint.joint.type) {
  44987. case BABYLON.PhysicsJoint.HingeJoint:
  44988. case BABYLON.PhysicsJoint.Hinge2Joint:
  44989. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  44990. break;
  44991. case BABYLON.PhysicsJoint.DistanceJoint:
  44992. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  44993. break;
  44994. case BABYLON.PhysicsJoint.SpringJoint:
  44995. var springData = jointData;
  44996. constraint = new CANNON.Spring(mainBody, connectedBody, {
  44997. restLength: springData.length,
  44998. stiffness: springData.stiffness,
  44999. damping: springData.damping,
  45000. localAnchorA: constraintData.pivotA,
  45001. localAnchorB: constraintData.pivotB
  45002. });
  45003. break;
  45004. case BABYLON.PhysicsJoint.LockJoint:
  45005. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45006. break;
  45007. case BABYLON.PhysicsJoint.PointToPointJoint:
  45008. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45009. default:
  45010. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45011. break;
  45012. }
  45013. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45014. constraint.collideConnected = !!jointData.collision;
  45015. impostorJoint.joint.physicsJoint = constraint;
  45016. //don't add spring as constraint, as it is not one.
  45017. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45018. this.world.addConstraint(constraint);
  45019. }
  45020. else {
  45021. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45022. constraint.applyForce();
  45023. });
  45024. }
  45025. };
  45026. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45027. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45028. };
  45029. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45030. var index;
  45031. var mat;
  45032. for (index = 0; index < this._physicsMaterials.length; index++) {
  45033. mat = this._physicsMaterials[index];
  45034. if (mat.friction === friction && mat.restitution === restitution) {
  45035. return mat;
  45036. }
  45037. }
  45038. var currentMat = new CANNON.Material(name);
  45039. currentMat.friction = friction;
  45040. currentMat.restitution = restitution;
  45041. this._physicsMaterials.push(currentMat);
  45042. return currentMat;
  45043. };
  45044. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45045. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45046. };
  45047. CannonJSPlugin.prototype._createShape = function (impostor) {
  45048. var object = impostor.object;
  45049. var returnValue;
  45050. var extendSize = impostor.getObjectExtendSize();
  45051. switch (impostor.type) {
  45052. case BABYLON.PhysicsImpostor.SphereImpostor:
  45053. var radiusX = extendSize.x;
  45054. var radiusY = extendSize.y;
  45055. var radiusZ = extendSize.z;
  45056. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  45057. break;
  45058. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  45059. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45060. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  45061. break;
  45062. case BABYLON.PhysicsImpostor.BoxImpostor:
  45063. var box = extendSize.scale(0.5);
  45064. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  45065. break;
  45066. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45067. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  45068. returnValue = new CANNON.Plane();
  45069. break;
  45070. case BABYLON.PhysicsImpostor.MeshImpostor:
  45071. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  45072. var rawFaces = object.getIndices ? object.getIndices() : [];
  45073. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  45074. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  45075. break;
  45076. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  45077. returnValue = this._createHeightmap(object);
  45078. break;
  45079. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45080. returnValue = new CANNON.Particle();
  45081. break;
  45082. }
  45083. return returnValue;
  45084. };
  45085. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  45086. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45087. var matrix = [];
  45088. //For now pointDepth will not be used and will be automatically calculated.
  45089. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  45090. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  45091. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  45092. var elementSize = dim * 2 / arraySize;
  45093. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  45094. for (var i = 0; i < pos.length; i = i + 3) {
  45095. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  45096. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  45097. var y = pos[i + 1] + minY;
  45098. if (!matrix[x]) {
  45099. matrix[x] = [];
  45100. }
  45101. if (!matrix[x][z]) {
  45102. matrix[x][z] = y;
  45103. }
  45104. matrix[x][z] = Math.max(y, matrix[x][z]);
  45105. }
  45106. for (var x = 0; x <= arraySize; ++x) {
  45107. if (!matrix[x]) {
  45108. var loc = 1;
  45109. while (!matrix[(x + loc) % arraySize]) {
  45110. loc++;
  45111. }
  45112. matrix[x] = matrix[(x + loc) % arraySize].slice();
  45113. }
  45114. for (var z = 0; z <= arraySize; ++z) {
  45115. if (!matrix[x][z]) {
  45116. var loc = 1;
  45117. var newValue;
  45118. while (newValue === undefined) {
  45119. newValue = matrix[x][(z + loc++) % arraySize];
  45120. }
  45121. matrix[x][z] = newValue;
  45122. }
  45123. }
  45124. }
  45125. var shape = new CANNON.Heightfield(matrix, {
  45126. elementSize: elementSize
  45127. });
  45128. //For future reference, needed for body transformation
  45129. shape.minY = minY;
  45130. return shape;
  45131. };
  45132. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  45133. var object = impostor.object;
  45134. //make sure it is updated...
  45135. object.computeWorldMatrix && object.computeWorldMatrix(true);
  45136. // The delta between the mesh position and the mesh bounding box center
  45137. var center = impostor.getObjectCenter();
  45138. var extendSize = impostor.getObjectExtendSize();
  45139. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  45140. this._tmpPosition.copyFrom(center);
  45141. var quaternion = object.rotationQuaternion;
  45142. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  45143. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  45144. //-90 DEG in X, precalculated
  45145. quaternion = quaternion.multiply(this._minus90X);
  45146. //Invert! (Precalculated, 90 deg in X)
  45147. //No need to clone. this will never change.
  45148. impostor.setDeltaRotation(this._plus90X);
  45149. }
  45150. //If it is a heightfield, if should be centered.
  45151. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  45152. var mesh = object;
  45153. //calculate the correct body position:
  45154. var rotationQuaternion = mesh.rotationQuaternion;
  45155. mesh.rotationQuaternion = this._tmpUnityRotation;
  45156. mesh.computeWorldMatrix(true);
  45157. //get original center with no rotation
  45158. var c = center.clone();
  45159. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  45160. //rotation is back
  45161. mesh.rotationQuaternion = rotationQuaternion;
  45162. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  45163. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  45164. mesh.setPivotMatrix(p);
  45165. mesh.computeWorldMatrix(true);
  45166. //calculate the translation
  45167. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  45168. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  45169. //add it inverted to the delta
  45170. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  45171. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  45172. mesh.setPivotMatrix(oldPivot);
  45173. mesh.computeWorldMatrix(true);
  45174. }
  45175. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  45176. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  45177. this._tmpPosition.copyFrom(object.position);
  45178. }
  45179. impostor.setDeltaPosition(this._tmpDeltaPosition);
  45180. //Now update the impostor object
  45181. impostor.physicsBody.position.copy(this._tmpPosition);
  45182. impostor.physicsBody.quaternion.copy(quaternion);
  45183. };
  45184. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45185. impostor.object.position.copyFrom(impostor.physicsBody.position);
  45186. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  45187. };
  45188. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  45189. impostor.physicsBody.position.copy(newPosition);
  45190. impostor.physicsBody.quaternion.copy(newRotation);
  45191. };
  45192. CannonJSPlugin.prototype.isSupported = function () {
  45193. return window.CANNON !== undefined;
  45194. };
  45195. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  45196. impostor.physicsBody.velocity.copy(velocity);
  45197. };
  45198. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  45199. impostor.physicsBody.angularVelocity.copy(velocity);
  45200. };
  45201. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  45202. var v = impostor.physicsBody.velocity;
  45203. if (!v)
  45204. return null;
  45205. return new BABYLON.Vector3(v.x, v.y, v.z);
  45206. };
  45207. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  45208. var v = impostor.physicsBody.angularVelocity;
  45209. if (!v)
  45210. return null;
  45211. return new BABYLON.Vector3(v.x, v.y, v.z);
  45212. };
  45213. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  45214. impostor.physicsBody.mass = mass;
  45215. impostor.physicsBody.updateMassProperties();
  45216. };
  45217. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  45218. impostor.physicsBody.sleep();
  45219. };
  45220. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  45221. impostor.physicsBody.wakeUp();
  45222. };
  45223. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  45224. joint.physicsJoint.distance = maxDistance;
  45225. };
  45226. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  45227. if (!motorIndex) {
  45228. joint.physicsJoint.enableMotor();
  45229. }
  45230. };
  45231. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  45232. if (!motorIndex) {
  45233. joint.physicsJoint.disableMotor();
  45234. }
  45235. };
  45236. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  45237. if (!motorIndex) {
  45238. joint.physicsJoint.enableMotor();
  45239. joint.physicsJoint.setMotorSpeed(speed);
  45240. if (maxForce) {
  45241. this.setLimit(joint, maxForce);
  45242. }
  45243. }
  45244. };
  45245. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  45246. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  45247. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  45248. };
  45249. CannonJSPlugin.prototype.dispose = function () {
  45250. //nothing to do, actually.
  45251. };
  45252. return CannonJSPlugin;
  45253. }());
  45254. BABYLON.CannonJSPlugin = CannonJSPlugin;
  45255. })(BABYLON || (BABYLON = {}));
  45256. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  45257. var BABYLON;
  45258. (function (BABYLON) {
  45259. var OimoJSPlugin = (function () {
  45260. function OimoJSPlugin(iterations) {
  45261. this.name = "OimoJSPlugin";
  45262. this._tmpImpostorsArray = [];
  45263. this._tmpPositionVector = BABYLON.Vector3.Zero();
  45264. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  45265. this.world.worldscale(1);
  45266. this.world.clear();
  45267. //making sure no stats are calculated
  45268. this.world.isNoStat = true;
  45269. }
  45270. OimoJSPlugin.prototype.setGravity = function (gravity) {
  45271. this.world.gravity.copy(gravity);
  45272. };
  45273. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  45274. this.world.timeStep = timeStep;
  45275. };
  45276. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  45277. var _this = this;
  45278. impostors.forEach(function (impostor) {
  45279. impostor.beforeStep();
  45280. });
  45281. this.world.step();
  45282. impostors.forEach(function (impostor) {
  45283. impostor.afterStep();
  45284. //update the ordered impostors array
  45285. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  45286. });
  45287. //check for collisions
  45288. var contact = this.world.contacts;
  45289. while (contact !== null) {
  45290. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  45291. contact = contact.next;
  45292. continue;
  45293. }
  45294. //is this body colliding with any other? get the impostor
  45295. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  45296. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  45297. if (!mainImpostor || !collidingImpostor) {
  45298. contact = contact.next;
  45299. continue;
  45300. }
  45301. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  45302. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  45303. contact = contact.next;
  45304. }
  45305. };
  45306. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45307. var mass = impostor.physicsBody.massInfo.mass;
  45308. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  45309. };
  45310. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45311. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  45312. this.applyImpulse(impostor, force, contactPoint);
  45313. };
  45314. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45315. var _this = this;
  45316. //parent-child relationship. Does this impostor has a parent impostor?
  45317. if (impostor.parent) {
  45318. if (impostor.physicsBody) {
  45319. this.removePhysicsBody(impostor);
  45320. //TODO is that needed?
  45321. impostor.forceUpdate();
  45322. }
  45323. return;
  45324. }
  45325. if (impostor.isBodyInitRequired()) {
  45326. var bodyConfig = {
  45327. name: impostor.uniqueId,
  45328. //Oimo must have mass, also for static objects.
  45329. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  45330. size: [],
  45331. type: [],
  45332. pos: [],
  45333. rot: [],
  45334. move: impostor.getParam("mass") !== 0,
  45335. //Supporting older versions of Oimo
  45336. world: this.world
  45337. };
  45338. var impostors = [impostor];
  45339. var addToArray = function (parent) {
  45340. if (!parent.getChildMeshes)
  45341. return;
  45342. parent.getChildMeshes().forEach(function (m) {
  45343. if (m.physicsImpostor) {
  45344. impostors.push(m.physicsImpostor);
  45345. m.physicsImpostor._init();
  45346. }
  45347. });
  45348. };
  45349. addToArray(impostor.object);
  45350. var checkWithEpsilon_1 = function (value) {
  45351. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  45352. };
  45353. impostors.forEach(function (i) {
  45354. //get the correct bounding box
  45355. var oldQuaternion = i.object.rotationQuaternion;
  45356. var rot = new OIMO.Euler().setFromQuaternion({
  45357. x: impostor.object.rotationQuaternion.x,
  45358. y: impostor.object.rotationQuaternion.y,
  45359. z: impostor.object.rotationQuaternion.z,
  45360. s: impostor.object.rotationQuaternion.w
  45361. });
  45362. var extendSize = i.getObjectExtendSize();
  45363. if (i === impostor) {
  45364. var center = impostor.getObjectCenter();
  45365. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  45366. //Can also use Array.prototype.push.apply
  45367. bodyConfig.pos.push(center.x);
  45368. bodyConfig.pos.push(center.y);
  45369. bodyConfig.pos.push(center.z);
  45370. //tmp solution
  45371. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  45372. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  45373. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  45374. }
  45375. else {
  45376. bodyConfig.pos.push(i.object.position.x);
  45377. bodyConfig.pos.push(i.object.position.y);
  45378. bodyConfig.pos.push(i.object.position.z);
  45379. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  45380. bodyConfig.rot.push(0);
  45381. bodyConfig.rot.push(0);
  45382. bodyConfig.rot.push(0);
  45383. }
  45384. // register mesh
  45385. switch (i.type) {
  45386. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45387. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  45388. case BABYLON.PhysicsImpostor.SphereImpostor:
  45389. var radiusX = extendSize.x;
  45390. var radiusY = extendSize.y;
  45391. var radiusZ = extendSize.z;
  45392. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  45393. bodyConfig.type.push('sphere');
  45394. //due to the way oimo works with compounds, add 3 times
  45395. bodyConfig.size.push(size);
  45396. bodyConfig.size.push(size);
  45397. bodyConfig.size.push(size);
  45398. break;
  45399. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45400. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  45401. var sizeY = checkWithEpsilon_1(extendSize.y);
  45402. bodyConfig.type.push('cylinder');
  45403. bodyConfig.size.push(sizeX);
  45404. bodyConfig.size.push(sizeY);
  45405. //due to the way oimo works with compounds, add one more value.
  45406. bodyConfig.size.push(sizeY);
  45407. break;
  45408. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45409. case BABYLON.PhysicsImpostor.BoxImpostor:
  45410. default:
  45411. var sizeX = checkWithEpsilon_1(extendSize.x);
  45412. var sizeY = checkWithEpsilon_1(extendSize.y);
  45413. var sizeZ = checkWithEpsilon_1(extendSize.z);
  45414. bodyConfig.type.push('box');
  45415. bodyConfig.size.push(sizeX);
  45416. bodyConfig.size.push(sizeY);
  45417. bodyConfig.size.push(sizeZ);
  45418. break;
  45419. }
  45420. //actually not needed, but hey...
  45421. i.object.rotationQuaternion = oldQuaternion;
  45422. });
  45423. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  45424. }
  45425. else {
  45426. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  45427. }
  45428. impostor.setDeltaPosition(this._tmpPositionVector);
  45429. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  45430. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  45431. };
  45432. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45433. //impostor.physicsBody.dispose();
  45434. //Same as : (older oimo versions)
  45435. this.world.removeRigidBody(impostor.physicsBody);
  45436. };
  45437. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45438. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45439. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45440. if (!mainBody || !connectedBody) {
  45441. return;
  45442. }
  45443. var jointData = impostorJoint.joint.jointData;
  45444. var options = jointData.nativeParams || {};
  45445. var type;
  45446. var nativeJointData = {
  45447. body1: mainBody,
  45448. body2: connectedBody,
  45449. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  45450. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  45451. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  45452. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  45453. min: options.min,
  45454. max: options.max,
  45455. collision: options.collision || jointData.collision,
  45456. spring: options.spring,
  45457. //supporting older version of Oimo
  45458. world: this.world
  45459. };
  45460. switch (impostorJoint.joint.type) {
  45461. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45462. type = "jointBall";
  45463. break;
  45464. case BABYLON.PhysicsJoint.SpringJoint:
  45465. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  45466. var springData = jointData;
  45467. nativeJointData.min = springData.length || nativeJointData.min;
  45468. //Max should also be set, just make sure it is at least min
  45469. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  45470. case BABYLON.PhysicsJoint.DistanceJoint:
  45471. type = "jointDistance";
  45472. nativeJointData.max = jointData.maxDistance;
  45473. break;
  45474. case BABYLON.PhysicsJoint.PrismaticJoint:
  45475. type = "jointPrisme";
  45476. break;
  45477. case BABYLON.PhysicsJoint.SliderJoint:
  45478. type = "jointSlide";
  45479. break;
  45480. case BABYLON.PhysicsJoint.WheelJoint:
  45481. type = "jointWheel";
  45482. break;
  45483. case BABYLON.PhysicsJoint.HingeJoint:
  45484. default:
  45485. type = "jointHinge";
  45486. break;
  45487. }
  45488. nativeJointData.type = type;
  45489. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  45490. };
  45491. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45492. //Bug in Oimo prevents us from disposing a joint in the playground
  45493. //joint.joint.physicsJoint.dispose();
  45494. //So we will bruteforce it!
  45495. try {
  45496. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  45497. }
  45498. catch (e) {
  45499. BABYLON.Tools.Warn(e);
  45500. }
  45501. };
  45502. OimoJSPlugin.prototype.isSupported = function () {
  45503. return OIMO !== undefined;
  45504. };
  45505. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45506. if (!impostor.physicsBody.sleeping) {
  45507. //TODO check that
  45508. if (impostor.physicsBody.shapes.next) {
  45509. var parentShape = this._getLastShape(impostor.physicsBody);
  45510. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  45511. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  45512. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  45513. }
  45514. else {
  45515. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  45516. }
  45517. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  45518. impostor.object.rotationQuaternion.normalize();
  45519. }
  45520. };
  45521. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  45522. var body = impostor.physicsBody;
  45523. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  45524. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  45525. body.syncShapes();
  45526. body.awake();
  45527. };
  45528. OimoJSPlugin.prototype._getLastShape = function (body) {
  45529. var lastShape = body.shapes;
  45530. while (lastShape.next) {
  45531. lastShape = lastShape.next;
  45532. }
  45533. return lastShape;
  45534. };
  45535. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  45536. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  45537. };
  45538. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  45539. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  45540. };
  45541. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  45542. var v = impostor.physicsBody.linearVelocity;
  45543. if (!v)
  45544. return null;
  45545. return new BABYLON.Vector3(v.x, v.y, v.z);
  45546. };
  45547. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  45548. var v = impostor.physicsBody.angularVelocity;
  45549. if (!v)
  45550. return null;
  45551. return new BABYLON.Vector3(v.x, v.y, v.z);
  45552. };
  45553. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  45554. var staticBody = mass === 0;
  45555. //this will actually set the body's density and not its mass.
  45556. //But this is how oimo treats the mass variable.
  45557. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  45558. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  45559. };
  45560. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  45561. impostor.physicsBody.sleep();
  45562. };
  45563. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  45564. impostor.physicsBody.awake();
  45565. };
  45566. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  45567. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  45568. if (minDistance !== void 0) {
  45569. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  45570. }
  45571. };
  45572. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  45573. //TODO separate rotational and transational motors.
  45574. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  45575. if (motor) {
  45576. motor.setMotor(speed, maxForce);
  45577. }
  45578. };
  45579. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  45580. //TODO separate rotational and transational motors.
  45581. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  45582. if (motor) {
  45583. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  45584. }
  45585. };
  45586. OimoJSPlugin.prototype.dispose = function () {
  45587. this.world.clear();
  45588. };
  45589. return OimoJSPlugin;
  45590. }());
  45591. BABYLON.OimoJSPlugin = OimoJSPlugin;
  45592. })(BABYLON || (BABYLON = {}));
  45593. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  45594. var BABYLON;
  45595. (function (BABYLON) {
  45596. var DisplayPassPostProcess = (function (_super) {
  45597. __extends(DisplayPassPostProcess, _super);
  45598. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45599. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  45600. }
  45601. return DisplayPassPostProcess;
  45602. }(BABYLON.PostProcess));
  45603. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  45604. })(BABYLON || (BABYLON = {}));
  45605. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  45606. var BABYLON;
  45607. (function (BABYLON) {
  45608. var SimplificationSettings = (function () {
  45609. function SimplificationSettings(quality, distance, optimizeMesh) {
  45610. this.quality = quality;
  45611. this.distance = distance;
  45612. this.optimizeMesh = optimizeMesh;
  45613. }
  45614. return SimplificationSettings;
  45615. }());
  45616. BABYLON.SimplificationSettings = SimplificationSettings;
  45617. var SimplificationQueue = (function () {
  45618. function SimplificationQueue() {
  45619. this.running = false;
  45620. this._simplificationArray = [];
  45621. }
  45622. SimplificationQueue.prototype.addTask = function (task) {
  45623. this._simplificationArray.push(task);
  45624. };
  45625. SimplificationQueue.prototype.executeNext = function () {
  45626. var task = this._simplificationArray.pop();
  45627. if (task) {
  45628. this.running = true;
  45629. this.runSimplification(task);
  45630. }
  45631. else {
  45632. this.running = false;
  45633. }
  45634. };
  45635. SimplificationQueue.prototype.runSimplification = function (task) {
  45636. var _this = this;
  45637. if (task.parallelProcessing) {
  45638. //parallel simplifier
  45639. task.settings.forEach(function (setting) {
  45640. var simplifier = _this.getSimplifier(task);
  45641. simplifier.simplify(setting, function (newMesh) {
  45642. task.mesh.addLODLevel(setting.distance, newMesh);
  45643. newMesh.isVisible = true;
  45644. //check if it is the last
  45645. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  45646. //all done, run the success callback.
  45647. task.successCallback();
  45648. }
  45649. _this.executeNext();
  45650. });
  45651. });
  45652. }
  45653. else {
  45654. //single simplifier.
  45655. var simplifier = this.getSimplifier(task);
  45656. var runDecimation = function (setting, callback) {
  45657. simplifier.simplify(setting, function (newMesh) {
  45658. task.mesh.addLODLevel(setting.distance, newMesh);
  45659. newMesh.isVisible = true;
  45660. //run the next quality level
  45661. callback();
  45662. });
  45663. };
  45664. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  45665. runDecimation(task.settings[loop.index], function () {
  45666. loop.executeNext();
  45667. });
  45668. }, function () {
  45669. //execution ended, run the success callback.
  45670. if (task.successCallback) {
  45671. task.successCallback();
  45672. }
  45673. _this.executeNext();
  45674. });
  45675. }
  45676. };
  45677. SimplificationQueue.prototype.getSimplifier = function (task) {
  45678. switch (task.simplificationType) {
  45679. case SimplificationType.QUADRATIC:
  45680. default:
  45681. return new QuadraticErrorSimplification(task.mesh);
  45682. }
  45683. };
  45684. return SimplificationQueue;
  45685. }());
  45686. BABYLON.SimplificationQueue = SimplificationQueue;
  45687. /**
  45688. * The implemented types of simplification.
  45689. * At the moment only Quadratic Error Decimation is implemented.
  45690. */
  45691. var SimplificationType;
  45692. (function (SimplificationType) {
  45693. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  45694. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  45695. var DecimationTriangle = (function () {
  45696. function DecimationTriangle(vertices) {
  45697. this.vertices = vertices;
  45698. this.error = new Array(4);
  45699. this.deleted = false;
  45700. this.isDirty = false;
  45701. this.deletePending = false;
  45702. this.borderFactor = 0;
  45703. }
  45704. return DecimationTriangle;
  45705. }());
  45706. BABYLON.DecimationTriangle = DecimationTriangle;
  45707. var DecimationVertex = (function () {
  45708. function DecimationVertex(position, id) {
  45709. this.position = position;
  45710. this.id = id;
  45711. this.isBorder = true;
  45712. this.q = new QuadraticMatrix();
  45713. this.triangleCount = 0;
  45714. this.triangleStart = 0;
  45715. this.originalOffsets = [];
  45716. }
  45717. DecimationVertex.prototype.updatePosition = function (newPosition) {
  45718. this.position.copyFrom(newPosition);
  45719. };
  45720. return DecimationVertex;
  45721. }());
  45722. BABYLON.DecimationVertex = DecimationVertex;
  45723. var QuadraticMatrix = (function () {
  45724. function QuadraticMatrix(data) {
  45725. this.data = new Array(10);
  45726. for (var i = 0; i < 10; ++i) {
  45727. if (data && data[i]) {
  45728. this.data[i] = data[i];
  45729. }
  45730. else {
  45731. this.data[i] = 0;
  45732. }
  45733. }
  45734. }
  45735. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  45736. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  45737. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  45738. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  45739. return det;
  45740. };
  45741. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  45742. for (var i = 0; i < 10; ++i) {
  45743. this.data[i] += matrix.data[i];
  45744. }
  45745. };
  45746. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  45747. for (var i = 0; i < 10; ++i) {
  45748. this.data[i] += data[i];
  45749. }
  45750. };
  45751. QuadraticMatrix.prototype.add = function (matrix) {
  45752. var m = new QuadraticMatrix();
  45753. for (var i = 0; i < 10; ++i) {
  45754. m.data[i] = this.data[i] + matrix.data[i];
  45755. }
  45756. return m;
  45757. };
  45758. QuadraticMatrix.FromData = function (a, b, c, d) {
  45759. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  45760. };
  45761. //returning an array to avoid garbage collection
  45762. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  45763. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  45764. };
  45765. return QuadraticMatrix;
  45766. }());
  45767. BABYLON.QuadraticMatrix = QuadraticMatrix;
  45768. var Reference = (function () {
  45769. function Reference(vertexId, triangleId) {
  45770. this.vertexId = vertexId;
  45771. this.triangleId = triangleId;
  45772. }
  45773. return Reference;
  45774. }());
  45775. BABYLON.Reference = Reference;
  45776. /**
  45777. * An implementation of the Quadratic Error simplification algorithm.
  45778. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  45779. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  45780. * @author RaananW
  45781. */
  45782. var QuadraticErrorSimplification = (function () {
  45783. function QuadraticErrorSimplification(_mesh) {
  45784. this._mesh = _mesh;
  45785. this.initialized = false;
  45786. this.syncIterations = 5000;
  45787. this.aggressiveness = 7;
  45788. this.decimationIterations = 100;
  45789. this.boundingBoxEpsilon = BABYLON.Epsilon;
  45790. }
  45791. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  45792. var _this = this;
  45793. this.initDecimatedMesh();
  45794. //iterating through the submeshes array, one after the other.
  45795. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  45796. _this.initWithMesh(loop.index, function () {
  45797. _this.runDecimation(settings, loop.index, function () {
  45798. loop.executeNext();
  45799. });
  45800. }, settings.optimizeMesh);
  45801. }, function () {
  45802. setTimeout(function () {
  45803. successCallback(_this._reconstructedMesh);
  45804. }, 0);
  45805. });
  45806. };
  45807. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  45808. var _this = this;
  45809. var gCount = 0;
  45810. triangle.vertices.forEach(function (vertex) {
  45811. var count = 0;
  45812. var vPos = vertex.position;
  45813. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  45814. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  45815. ++count;
  45816. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  45817. ++count;
  45818. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  45819. ++count;
  45820. if (count > 1) {
  45821. ++gCount;
  45822. }
  45823. ;
  45824. });
  45825. if (gCount > 1) {
  45826. console.log(triangle, gCount);
  45827. }
  45828. return gCount > 1;
  45829. };
  45830. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  45831. var _this = this;
  45832. var targetCount = ~~(this.triangles.length * settings.quality);
  45833. var deletedTriangles = 0;
  45834. var triangleCount = this.triangles.length;
  45835. var iterationFunction = function (iteration, callback) {
  45836. setTimeout(function () {
  45837. if (iteration % 5 === 0) {
  45838. _this.updateMesh(iteration === 0);
  45839. }
  45840. for (var i = 0; i < _this.triangles.length; ++i) {
  45841. _this.triangles[i].isDirty = false;
  45842. }
  45843. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  45844. var trianglesIterator = function (i) {
  45845. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  45846. var t = _this.triangles[tIdx];
  45847. if (!t)
  45848. return;
  45849. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  45850. return;
  45851. }
  45852. for (var j = 0; j < 3; ++j) {
  45853. if (t.error[j] < threshold) {
  45854. var deleted0 = [];
  45855. var deleted1 = [];
  45856. var v0 = t.vertices[j];
  45857. var v1 = t.vertices[(j + 1) % 3];
  45858. if (v0.isBorder || v1.isBorder)
  45859. continue;
  45860. var p = BABYLON.Vector3.Zero();
  45861. var n = BABYLON.Vector3.Zero();
  45862. var uv = BABYLON.Vector2.Zero();
  45863. var color = new BABYLON.Color4(0, 0, 0, 1);
  45864. _this.calculateError(v0, v1, p, n, uv, color);
  45865. var delTr = [];
  45866. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  45867. continue;
  45868. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  45869. continue;
  45870. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  45871. continue;
  45872. var uniqueArray = [];
  45873. delTr.forEach(function (deletedT) {
  45874. if (uniqueArray.indexOf(deletedT) === -1) {
  45875. deletedT.deletePending = true;
  45876. uniqueArray.push(deletedT);
  45877. }
  45878. });
  45879. if (uniqueArray.length % 2 !== 0) {
  45880. continue;
  45881. }
  45882. v0.q = v1.q.add(v0.q);
  45883. v0.updatePosition(p);
  45884. var tStart = _this.references.length;
  45885. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  45886. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  45887. var tCount = _this.references.length - tStart;
  45888. if (tCount <= v0.triangleCount) {
  45889. if (tCount) {
  45890. for (var c = 0; c < tCount; c++) {
  45891. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  45892. }
  45893. }
  45894. }
  45895. else {
  45896. v0.triangleStart = tStart;
  45897. }
  45898. v0.triangleCount = tCount;
  45899. break;
  45900. }
  45901. }
  45902. };
  45903. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  45904. }, 0);
  45905. };
  45906. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  45907. if (triangleCount - deletedTriangles <= targetCount)
  45908. loop.breakLoop();
  45909. else {
  45910. iterationFunction(loop.index, function () {
  45911. loop.executeNext();
  45912. });
  45913. }
  45914. }, function () {
  45915. setTimeout(function () {
  45916. //reconstruct this part of the mesh
  45917. _this.reconstructMesh(submeshIndex);
  45918. successCallback();
  45919. }, 0);
  45920. });
  45921. };
  45922. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  45923. var _this = this;
  45924. this.vertices = [];
  45925. this.triangles = [];
  45926. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45927. var indices = this._mesh.getIndices();
  45928. var submesh = this._mesh.subMeshes[submeshIndex];
  45929. var findInVertices = function (positionToSearch) {
  45930. if (optimizeMesh) {
  45931. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  45932. if (_this.vertices[ii].position.equals(positionToSearch)) {
  45933. return _this.vertices[ii];
  45934. }
  45935. }
  45936. }
  45937. return null;
  45938. };
  45939. var vertexReferences = [];
  45940. var vertexInit = function (i) {
  45941. var offset = i + submesh.verticesStart;
  45942. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  45943. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  45944. vertex.originalOffsets.push(offset);
  45945. if (vertex.id === _this.vertices.length) {
  45946. _this.vertices.push(vertex);
  45947. }
  45948. vertexReferences.push(vertex.id);
  45949. };
  45950. //var totalVertices = mesh.getTotalVertices();
  45951. var totalVertices = submesh.verticesCount;
  45952. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  45953. var indicesInit = function (i) {
  45954. var offset = (submesh.indexStart / 3) + i;
  45955. var pos = (offset * 3);
  45956. var i0 = indices[pos + 0];
  45957. var i1 = indices[pos + 1];
  45958. var i2 = indices[pos + 2];
  45959. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  45960. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  45961. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  45962. var triangle = new DecimationTriangle([v0, v1, v2]);
  45963. triangle.originalOffset = pos;
  45964. _this.triangles.push(triangle);
  45965. };
  45966. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  45967. _this.init(callback);
  45968. });
  45969. });
  45970. };
  45971. QuadraticErrorSimplification.prototype.init = function (callback) {
  45972. var _this = this;
  45973. var triangleInit1 = function (i) {
  45974. var t = _this.triangles[i];
  45975. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  45976. for (var j = 0; j < 3; j++) {
  45977. 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))));
  45978. }
  45979. };
  45980. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  45981. var triangleInit2 = function (i) {
  45982. var t = _this.triangles[i];
  45983. for (var j = 0; j < 3; ++j) {
  45984. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  45985. }
  45986. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  45987. };
  45988. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  45989. _this.initialized = true;
  45990. callback();
  45991. });
  45992. });
  45993. };
  45994. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  45995. var newTriangles = [];
  45996. var i;
  45997. for (i = 0; i < this.vertices.length; ++i) {
  45998. this.vertices[i].triangleCount = 0;
  45999. }
  46000. var t;
  46001. var j;
  46002. for (i = 0; i < this.triangles.length; ++i) {
  46003. if (!this.triangles[i].deleted) {
  46004. t = this.triangles[i];
  46005. for (j = 0; j < 3; ++j) {
  46006. t.vertices[j].triangleCount = 1;
  46007. }
  46008. newTriangles.push(t);
  46009. }
  46010. }
  46011. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46012. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46013. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46014. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46015. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46016. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46017. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46018. var vertexCount = 0;
  46019. for (i = 0; i < this.vertices.length; ++i) {
  46020. var vertex = this.vertices[i];
  46021. vertex.id = vertexCount;
  46022. if (vertex.triangleCount) {
  46023. vertex.originalOffsets.forEach(function (originalOffset) {
  46024. newPositionData.push(vertex.position.x);
  46025. newPositionData.push(vertex.position.y);
  46026. newPositionData.push(vertex.position.z);
  46027. newNormalData.push(normalData[originalOffset * 3]);
  46028. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46029. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46030. if (uvs && uvs.length) {
  46031. newUVsData.push(uvs[(originalOffset * 2)]);
  46032. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46033. }
  46034. else if (colorsData && colorsData.length) {
  46035. newColorsData.push(colorsData[(originalOffset * 4)]);
  46036. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46037. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46038. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46039. }
  46040. ++vertexCount;
  46041. });
  46042. }
  46043. }
  46044. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46045. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46046. var submeshesArray = this._reconstructedMesh.subMeshes;
  46047. this._reconstructedMesh.subMeshes = [];
  46048. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46049. var originalIndices = this._mesh.getIndices();
  46050. for (i = 0; i < newTriangles.length; ++i) {
  46051. t = newTriangles[i]; //now get the new referencing point for each vertex
  46052. [0, 1, 2].forEach(function (idx) {
  46053. var id = originalIndices[t.originalOffset + idx];
  46054. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46055. if (offset < 0)
  46056. offset = 0;
  46057. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  46058. });
  46059. }
  46060. //overwriting the old vertex buffers and indices.
  46061. this._reconstructedMesh.setIndices(newIndicesArray);
  46062. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  46063. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  46064. if (newUVsData.length > 0)
  46065. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  46066. if (newColorsData.length > 0)
  46067. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  46068. //create submesh
  46069. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  46070. if (submeshIndex > 0) {
  46071. this._reconstructedMesh.subMeshes = [];
  46072. submeshesArray.forEach(function (submesh) {
  46073. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  46074. });
  46075. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  46076. }
  46077. };
  46078. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  46079. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  46080. this._reconstructedMesh.material = this._mesh.material;
  46081. this._reconstructedMesh.parent = this._mesh.parent;
  46082. this._reconstructedMesh.isVisible = false;
  46083. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  46084. };
  46085. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  46086. for (var i = 0; i < vertex1.triangleCount; ++i) {
  46087. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  46088. if (t.deleted)
  46089. continue;
  46090. var s = this.references[vertex1.triangleStart + i].vertexId;
  46091. var v1 = t.vertices[(s + 1) % 3];
  46092. var v2 = t.vertices[(s + 2) % 3];
  46093. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  46094. deletedArray[i] = true;
  46095. delTr.push(t);
  46096. continue;
  46097. }
  46098. var d1 = v1.position.subtract(point);
  46099. d1 = d1.normalize();
  46100. var d2 = v2.position.subtract(point);
  46101. d2 = d2.normalize();
  46102. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  46103. return true;
  46104. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  46105. deletedArray[i] = false;
  46106. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  46107. return true;
  46108. }
  46109. return false;
  46110. };
  46111. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  46112. var newDeleted = deletedTriangles;
  46113. for (var i = 0; i < vertex.triangleCount; ++i) {
  46114. var ref = this.references[vertex.triangleStart + i];
  46115. var t = this.triangles[ref.triangleId];
  46116. if (t.deleted)
  46117. continue;
  46118. if (deletedArray[i] && t.deletePending) {
  46119. t.deleted = true;
  46120. newDeleted++;
  46121. continue;
  46122. }
  46123. t.vertices[ref.vertexId] = origVertex;
  46124. t.isDirty = true;
  46125. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  46126. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  46127. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  46128. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46129. this.references.push(ref);
  46130. }
  46131. return newDeleted;
  46132. };
  46133. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  46134. for (var i = 0; i < this.vertices.length; ++i) {
  46135. var vCount = [];
  46136. var vId = [];
  46137. var v = this.vertices[i];
  46138. var j;
  46139. for (j = 0; j < v.triangleCount; ++j) {
  46140. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  46141. for (var ii = 0; ii < 3; ii++) {
  46142. var ofs = 0;
  46143. var vv = triangle.vertices[ii];
  46144. while (ofs < vCount.length) {
  46145. if (vId[ofs] === vv.id)
  46146. break;
  46147. ++ofs;
  46148. }
  46149. if (ofs === vCount.length) {
  46150. vCount.push(1);
  46151. vId.push(vv.id);
  46152. }
  46153. else {
  46154. vCount[ofs]++;
  46155. }
  46156. }
  46157. }
  46158. for (j = 0; j < vCount.length; ++j) {
  46159. if (vCount[j] === 1) {
  46160. this.vertices[vId[j]].isBorder = true;
  46161. }
  46162. else {
  46163. this.vertices[vId[j]].isBorder = false;
  46164. }
  46165. }
  46166. }
  46167. };
  46168. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  46169. if (identifyBorders === void 0) { identifyBorders = false; }
  46170. var i;
  46171. if (!identifyBorders) {
  46172. var newTrianglesVector = [];
  46173. for (i = 0; i < this.triangles.length; ++i) {
  46174. if (!this.triangles[i].deleted) {
  46175. newTrianglesVector.push(this.triangles[i]);
  46176. }
  46177. }
  46178. this.triangles = newTrianglesVector;
  46179. }
  46180. for (i = 0; i < this.vertices.length; ++i) {
  46181. this.vertices[i].triangleCount = 0;
  46182. this.vertices[i].triangleStart = 0;
  46183. }
  46184. var t;
  46185. var j;
  46186. var v;
  46187. for (i = 0; i < this.triangles.length; ++i) {
  46188. t = this.triangles[i];
  46189. for (j = 0; j < 3; ++j) {
  46190. v = t.vertices[j];
  46191. v.triangleCount++;
  46192. }
  46193. }
  46194. var tStart = 0;
  46195. for (i = 0; i < this.vertices.length; ++i) {
  46196. this.vertices[i].triangleStart = tStart;
  46197. tStart += this.vertices[i].triangleCount;
  46198. this.vertices[i].triangleCount = 0;
  46199. }
  46200. var newReferences = new Array(this.triangles.length * 3);
  46201. for (i = 0; i < this.triangles.length; ++i) {
  46202. t = this.triangles[i];
  46203. for (j = 0; j < 3; ++j) {
  46204. v = t.vertices[j];
  46205. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  46206. v.triangleCount++;
  46207. }
  46208. }
  46209. this.references = newReferences;
  46210. if (identifyBorders) {
  46211. this.identifyBorder();
  46212. }
  46213. };
  46214. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  46215. var x = point.x;
  46216. var y = point.y;
  46217. var z = point.z;
  46218. 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
  46219. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  46220. };
  46221. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  46222. var q = vertex1.q.add(vertex2.q);
  46223. var border = vertex1.isBorder && vertex2.isBorder;
  46224. var error = 0;
  46225. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  46226. if (qDet !== 0 && !border) {
  46227. if (!pointResult) {
  46228. pointResult = BABYLON.Vector3.Zero();
  46229. }
  46230. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  46231. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  46232. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  46233. error = this.vertexError(q, pointResult);
  46234. }
  46235. else {
  46236. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  46237. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  46238. var error1 = this.vertexError(q, vertex1.position);
  46239. var error2 = this.vertexError(q, vertex2.position);
  46240. var error3 = this.vertexError(q, p3);
  46241. error = Math.min(error1, error2, error3);
  46242. if (error === error1) {
  46243. if (pointResult) {
  46244. pointResult.copyFrom(vertex1.position);
  46245. }
  46246. }
  46247. else if (error === error2) {
  46248. if (pointResult) {
  46249. pointResult.copyFrom(vertex2.position);
  46250. }
  46251. }
  46252. else {
  46253. if (pointResult) {
  46254. pointResult.copyFrom(p3);
  46255. }
  46256. }
  46257. }
  46258. return error;
  46259. };
  46260. return QuadraticErrorSimplification;
  46261. }());
  46262. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  46263. })(BABYLON || (BABYLON = {}));
  46264. //# sourceMappingURL=babylon.meshSimplification.js.map
  46265. var BABYLON;
  46266. (function (BABYLON) {
  46267. var serializedGeometries = [];
  46268. var serializeGeometry = function (geometry, serializationGeometries) {
  46269. if (serializedGeometries[geometry.id]) {
  46270. return;
  46271. }
  46272. if (geometry.doNotSerialize) {
  46273. return;
  46274. }
  46275. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  46276. serializationGeometries.boxes.push(geometry.serialize());
  46277. }
  46278. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  46279. serializationGeometries.spheres.push(geometry.serialize());
  46280. }
  46281. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  46282. serializationGeometries.cylinders.push(geometry.serialize());
  46283. }
  46284. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  46285. serializationGeometries.toruses.push(geometry.serialize());
  46286. }
  46287. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  46288. serializationGeometries.grounds.push(geometry.serialize());
  46289. }
  46290. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  46291. serializationGeometries.planes.push(geometry.serialize());
  46292. }
  46293. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  46294. serializationGeometries.torusKnots.push(geometry.serialize());
  46295. }
  46296. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  46297. throw new Error("Unknown primitive type");
  46298. }
  46299. else {
  46300. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  46301. }
  46302. serializedGeometries[geometry.id] = true;
  46303. };
  46304. var serializeMesh = function (mesh, serializationScene) {
  46305. var serializationObject = {};
  46306. // Geometry
  46307. var geometry = mesh._geometry;
  46308. if (geometry) {
  46309. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  46310. // 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
  46311. serializeGeometry(geometry, serializationScene.geometries);
  46312. }
  46313. }
  46314. // Custom
  46315. if (mesh.serialize) {
  46316. mesh.serialize(serializationObject);
  46317. }
  46318. return serializationObject;
  46319. };
  46320. var finalizeSingleMesh = function (mesh, serializationObject) {
  46321. //only works if the mesh is already loaded
  46322. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  46323. //serialize material
  46324. if (mesh.material) {
  46325. if (mesh.material instanceof BABYLON.StandardMaterial) {
  46326. serializationObject.materials = serializationObject.materials || [];
  46327. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  46328. serializationObject.materials.push(mesh.material.serialize());
  46329. }
  46330. }
  46331. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  46332. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  46333. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  46334. serializationObject.multiMaterials.push(mesh.material.serialize());
  46335. }
  46336. }
  46337. }
  46338. //serialize geometry
  46339. var geometry = mesh._geometry;
  46340. if (geometry) {
  46341. if (!serializationObject.geometries) {
  46342. serializationObject.geometries = {};
  46343. serializationObject.geometries.boxes = [];
  46344. serializationObject.geometries.spheres = [];
  46345. serializationObject.geometries.cylinders = [];
  46346. serializationObject.geometries.toruses = [];
  46347. serializationObject.geometries.grounds = [];
  46348. serializationObject.geometries.planes = [];
  46349. serializationObject.geometries.torusKnots = [];
  46350. serializationObject.geometries.vertexData = [];
  46351. }
  46352. serializeGeometry(geometry, serializationObject.geometries);
  46353. }
  46354. // Skeletons
  46355. if (mesh.skeleton) {
  46356. serializationObject.skeletons = serializationObject.skeletons || [];
  46357. serializationObject.skeletons.push(mesh.skeleton.serialize());
  46358. }
  46359. //serialize the actual mesh
  46360. serializationObject.meshes = serializationObject.meshes || [];
  46361. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  46362. }
  46363. };
  46364. var SceneSerializer = (function () {
  46365. function SceneSerializer() {
  46366. }
  46367. SceneSerializer.ClearCache = function () {
  46368. serializedGeometries = [];
  46369. };
  46370. SceneSerializer.Serialize = function (scene) {
  46371. var serializationObject = {};
  46372. SceneSerializer.ClearCache();
  46373. // Scene
  46374. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  46375. serializationObject.autoClear = scene.autoClear;
  46376. serializationObject.clearColor = scene.clearColor.asArray();
  46377. serializationObject.ambientColor = scene.ambientColor.asArray();
  46378. serializationObject.gravity = scene.gravity.asArray();
  46379. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  46380. serializationObject.workerCollisions = scene.workerCollisions;
  46381. // Fog
  46382. if (scene.fogMode && scene.fogMode !== 0) {
  46383. serializationObject.fogMode = scene.fogMode;
  46384. serializationObject.fogColor = scene.fogColor.asArray();
  46385. serializationObject.fogStart = scene.fogStart;
  46386. serializationObject.fogEnd = scene.fogEnd;
  46387. serializationObject.fogDensity = scene.fogDensity;
  46388. }
  46389. //Physics
  46390. if (scene.isPhysicsEnabled()) {
  46391. serializationObject.physicsEnabled = true;
  46392. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  46393. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  46394. }
  46395. // Metadata
  46396. if (scene.metadata) {
  46397. serializationObject.metadata = scene.metadata;
  46398. }
  46399. // Lights
  46400. serializationObject.lights = [];
  46401. var index;
  46402. var light;
  46403. for (index = 0; index < scene.lights.length; index++) {
  46404. light = scene.lights[index];
  46405. if (!light.doNotSerialize) {
  46406. serializationObject.lights.push(light.serialize());
  46407. }
  46408. }
  46409. // Cameras
  46410. serializationObject.cameras = [];
  46411. for (index = 0; index < scene.cameras.length; index++) {
  46412. var camera = scene.cameras[index];
  46413. if (!camera.doNotSerialize) {
  46414. serializationObject.cameras.push(camera.serialize());
  46415. }
  46416. }
  46417. if (scene.activeCamera) {
  46418. serializationObject.activeCameraID = scene.activeCamera.id;
  46419. }
  46420. // Animations
  46421. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  46422. // Materials
  46423. serializationObject.materials = [];
  46424. serializationObject.multiMaterials = [];
  46425. var material;
  46426. for (index = 0; index < scene.materials.length; index++) {
  46427. material = scene.materials[index];
  46428. if (!material.doNotSerialize) {
  46429. serializationObject.materials.push(material.serialize());
  46430. }
  46431. }
  46432. // MultiMaterials
  46433. serializationObject.multiMaterials = [];
  46434. for (index = 0; index < scene.multiMaterials.length; index++) {
  46435. var multiMaterial = scene.multiMaterials[index];
  46436. serializationObject.multiMaterials.push(multiMaterial.serialize());
  46437. }
  46438. // Skeletons
  46439. serializationObject.skeletons = [];
  46440. for (index = 0; index < scene.skeletons.length; index++) {
  46441. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  46442. }
  46443. // Geometries
  46444. serializationObject.geometries = {};
  46445. serializationObject.geometries.boxes = [];
  46446. serializationObject.geometries.spheres = [];
  46447. serializationObject.geometries.cylinders = [];
  46448. serializationObject.geometries.toruses = [];
  46449. serializationObject.geometries.grounds = [];
  46450. serializationObject.geometries.planes = [];
  46451. serializationObject.geometries.torusKnots = [];
  46452. serializationObject.geometries.vertexData = [];
  46453. serializedGeometries = [];
  46454. var geometries = scene.getGeometries();
  46455. for (index = 0; index < geometries.length; index++) {
  46456. var geometry = geometries[index];
  46457. if (geometry.isReady()) {
  46458. serializeGeometry(geometry, serializationObject.geometries);
  46459. }
  46460. }
  46461. // Meshes
  46462. serializationObject.meshes = [];
  46463. for (index = 0; index < scene.meshes.length; index++) {
  46464. var abstractMesh = scene.meshes[index];
  46465. if (abstractMesh instanceof BABYLON.Mesh) {
  46466. var mesh = abstractMesh;
  46467. if (!mesh.doNotSerialize) {
  46468. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  46469. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  46470. }
  46471. }
  46472. }
  46473. }
  46474. // Particles Systems
  46475. serializationObject.particleSystems = [];
  46476. for (index = 0; index < scene.particleSystems.length; index++) {
  46477. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  46478. }
  46479. // Lens flares
  46480. serializationObject.lensFlareSystems = [];
  46481. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  46482. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  46483. }
  46484. // Shadows
  46485. serializationObject.shadowGenerators = [];
  46486. for (index = 0; index < scene.lights.length; index++) {
  46487. light = scene.lights[index];
  46488. var shadowGenerator = light.getShadowGenerator();
  46489. // Only support serialization for official generator so far.
  46490. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  46491. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  46492. }
  46493. }
  46494. // Action Manager
  46495. if (scene.actionManager) {
  46496. serializationObject.actions = scene.actionManager.serialize("scene");
  46497. }
  46498. // Audio
  46499. serializationObject.sounds = [];
  46500. for (index = 0; index < scene.soundTracks.length; index++) {
  46501. var soundtrack = scene.soundTracks[index];
  46502. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  46503. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  46504. }
  46505. }
  46506. return serializationObject;
  46507. };
  46508. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  46509. if (withParents === void 0) { withParents = false; }
  46510. if (withChildren === void 0) { withChildren = false; }
  46511. var serializationObject = {};
  46512. SceneSerializer.ClearCache();
  46513. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  46514. if (withParents || withChildren) {
  46515. //deliberate for loop! not for each, appended should be processed as well.
  46516. for (var i = 0; i < toSerialize.length; ++i) {
  46517. if (withChildren) {
  46518. toSerialize[i].getDescendants().forEach(function (node) {
  46519. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  46520. toSerialize.push(node);
  46521. }
  46522. });
  46523. }
  46524. //make sure the array doesn't contain the object already
  46525. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  46526. toSerialize.push(toSerialize[i].parent);
  46527. }
  46528. }
  46529. }
  46530. toSerialize.forEach(function (mesh) {
  46531. finalizeSingleMesh(mesh, serializationObject);
  46532. });
  46533. return serializationObject;
  46534. };
  46535. return SceneSerializer;
  46536. }());
  46537. BABYLON.SceneSerializer = SceneSerializer;
  46538. })(BABYLON || (BABYLON = {}));
  46539. //# sourceMappingURL=babylon.sceneSerializer.js.map
  46540. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  46541. // Huge respect for a such great lib.
  46542. // Earcut license:
  46543. // Copyright (c) 2016, Mapbox
  46544. //
  46545. // Permission to use, copy, modify, and/or distribute this software for any purpose
  46546. // with or without fee is hereby granted, provided that the above copyright notice
  46547. // and this permission notice appear in all copies.
  46548. //
  46549. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  46550. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  46551. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  46552. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  46553. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  46554. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  46555. // THIS SOFTWARE.
  46556. var Earcut;
  46557. (function (Earcut) {
  46558. /**
  46559. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  46560. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  46561. * @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).
  46562. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  46563. */
  46564. function earcut(data, holeIndices, dim) {
  46565. dim = dim || 2;
  46566. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  46567. if (!outerNode)
  46568. return triangles;
  46569. var minX, minY, maxX, maxY, x, y, size;
  46570. if (hasHoles)
  46571. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  46572. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  46573. if (data.length > 80 * dim) {
  46574. minX = maxX = data[0];
  46575. minY = maxY = data[1];
  46576. for (var i = dim; i < outerLen; i += dim) {
  46577. x = data[i];
  46578. y = data[i + 1];
  46579. if (x < minX)
  46580. minX = x;
  46581. if (y < minY)
  46582. minY = y;
  46583. if (x > maxX)
  46584. maxX = x;
  46585. if (y > maxY)
  46586. maxY = y;
  46587. }
  46588. // minX, minY and size are later used to transform coords into integers for z-order calculation
  46589. size = Math.max(maxX - minX, maxY - minY);
  46590. }
  46591. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  46592. return triangles;
  46593. }
  46594. Earcut.earcut = earcut;
  46595. // create a circular doubly linked list from polygon points in the specified winding order
  46596. function linkedList(data, start, end, dim, clockwise) {
  46597. var i, last;
  46598. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  46599. for (i = start; i < end; i += dim)
  46600. last = insertNode(i, data[i], data[i + 1], last);
  46601. }
  46602. else {
  46603. for (i = end - dim; i >= start; i -= dim)
  46604. last = insertNode(i, data[i], data[i + 1], last);
  46605. }
  46606. if (last && equals(last, last.next)) {
  46607. removeNode(last);
  46608. last = last.next;
  46609. }
  46610. return last;
  46611. }
  46612. // eliminate colinear or duplicate points
  46613. function filterPoints(start, end) {
  46614. if (!start)
  46615. return start;
  46616. if (!end)
  46617. end = start;
  46618. var p = start, again;
  46619. do {
  46620. again = false;
  46621. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  46622. removeNode(p);
  46623. p = end = p.prev;
  46624. if (p === p.next)
  46625. return null;
  46626. again = true;
  46627. }
  46628. else {
  46629. p = p.next;
  46630. }
  46631. } while (again || p !== end);
  46632. return end;
  46633. }
  46634. // main ear slicing loop which triangulates a polygon (given as a linked list)
  46635. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  46636. if (!ear)
  46637. return;
  46638. // interlink polygon nodes in z-order
  46639. if (!pass && size)
  46640. indexCurve(ear, minX, minY, size);
  46641. var stop = ear, prev, next;
  46642. // iterate through ears, slicing them one by one
  46643. while (ear.prev !== ear.next) {
  46644. prev = ear.prev;
  46645. next = ear.next;
  46646. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  46647. // cut off the triangle
  46648. triangles.push(prev.i / dim);
  46649. triangles.push(ear.i / dim);
  46650. triangles.push(next.i / dim);
  46651. removeNode(ear);
  46652. // skipping the next vertice leads to less sliver triangles
  46653. ear = next.next;
  46654. stop = next.next;
  46655. continue;
  46656. }
  46657. ear = next;
  46658. // if we looped through the whole remaining polygon and can't find any more ears
  46659. if (ear === stop) {
  46660. // try filtering points and slicing again
  46661. if (!pass) {
  46662. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  46663. }
  46664. else if (pass === 1) {
  46665. ear = cureLocalIntersections(ear, triangles, dim);
  46666. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  46667. }
  46668. else if (pass === 2) {
  46669. splitEarcut(ear, triangles, dim, minX, minY, size);
  46670. }
  46671. break;
  46672. }
  46673. }
  46674. }
  46675. // check whether a polygon node forms a valid ear with adjacent nodes
  46676. function isEar(ear) {
  46677. var a = ear.prev, b = ear, c = ear.next;
  46678. if (area(a, b, c) >= 0)
  46679. return false; // reflex, can't be an ear
  46680. // now make sure we don't have other points inside the potential ear
  46681. var p = ear.next.next;
  46682. while (p !== ear.prev) {
  46683. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46684. area(p.prev, p, p.next) >= 0)
  46685. return false;
  46686. p = p.next;
  46687. }
  46688. return true;
  46689. }
  46690. function isEarHashed(ear, minX, minY, size) {
  46691. var a = ear.prev, b = ear, c = ear.next;
  46692. if (area(a, b, c) >= 0)
  46693. return false; // reflex, can't be an ear
  46694. // triangle bbox; min & max are calculated like this for speed
  46695. 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);
  46696. // z-order range for the current triangle bbox;
  46697. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  46698. // first look for points inside the triangle in increasing z-order
  46699. var p = ear.nextZ;
  46700. while (p && p.z <= maxZ) {
  46701. if (p !== ear.prev &&
  46702. p !== ear.next &&
  46703. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46704. area(p.prev, p, p.next) >= 0)
  46705. return false;
  46706. p = p.nextZ;
  46707. }
  46708. // then look for points in decreasing z-order
  46709. p = ear.prevZ;
  46710. while (p && p.z >= minZ) {
  46711. if (p !== ear.prev &&
  46712. p !== ear.next &&
  46713. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  46714. area(p.prev, p, p.next) >= 0)
  46715. return false;
  46716. p = p.prevZ;
  46717. }
  46718. return true;
  46719. }
  46720. // go through all polygon nodes and cure small local self-intersections
  46721. function cureLocalIntersections(start, triangles, dim) {
  46722. var p = start;
  46723. do {
  46724. var a = p.prev, b = p.next.next;
  46725. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  46726. triangles.push(a.i / dim);
  46727. triangles.push(p.i / dim);
  46728. triangles.push(b.i / dim);
  46729. // remove two nodes involved
  46730. removeNode(p);
  46731. removeNode(p.next);
  46732. p = start = b;
  46733. }
  46734. p = p.next;
  46735. } while (p !== start);
  46736. return p;
  46737. }
  46738. // try splitting polygon into two and triangulate them independently
  46739. function splitEarcut(start, triangles, dim, minX, minY, size) {
  46740. // look for a valid diagonal that divides the polygon into two
  46741. var a = start;
  46742. do {
  46743. var b = a.next.next;
  46744. while (b !== a.prev) {
  46745. if (a.i !== b.i && isValidDiagonal(a, b)) {
  46746. // split the polygon in two by the diagonal
  46747. var c = splitPolygon(a, b);
  46748. // filter colinear points around the cuts
  46749. a = filterPoints(a, a.next);
  46750. c = filterPoints(c, c.next);
  46751. // run earcut on each half
  46752. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  46753. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  46754. return;
  46755. }
  46756. b = b.next;
  46757. }
  46758. a = a.next;
  46759. } while (a !== start);
  46760. }
  46761. // link every hole into the outer loop, producing a single-ring polygon without holes
  46762. function eliminateHoles(data, holeIndices, outerNode, dim) {
  46763. var queue = [], i, len, start, end, list;
  46764. for (i = 0, len = holeIndices.length; i < len; i++) {
  46765. start = holeIndices[i] * dim;
  46766. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  46767. list = linkedList(data, start, end, dim, false);
  46768. if (list === list.next)
  46769. list.steiner = true;
  46770. queue.push(getLeftmost(list));
  46771. }
  46772. queue.sort(compareX);
  46773. // process holes from left to right
  46774. for (i = 0; i < queue.length; i++) {
  46775. eliminateHole(queue[i], outerNode);
  46776. outerNode = filterPoints(outerNode, outerNode.next);
  46777. }
  46778. return outerNode;
  46779. }
  46780. function compareX(a, b) {
  46781. return a.x - b.x;
  46782. }
  46783. // find a bridge between vertices that connects hole with an outer ring and and link it
  46784. function eliminateHole(hole, outerNode) {
  46785. outerNode = findHoleBridge(hole, outerNode);
  46786. if (outerNode) {
  46787. var b = splitPolygon(outerNode, hole);
  46788. filterPoints(b, b.next);
  46789. }
  46790. }
  46791. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  46792. function findHoleBridge(hole, outerNode) {
  46793. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  46794. // find a segment intersected by a ray from the hole's leftmost point to the left;
  46795. // segment's endpoint with lesser x will be potential connection point
  46796. do {
  46797. if (hy <= p.y && hy >= p.next.y) {
  46798. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  46799. if (x <= hx && x > qx) {
  46800. qx = x;
  46801. if (x === hx) {
  46802. if (hy === p.y)
  46803. return p;
  46804. if (hy === p.next.y)
  46805. return p.next;
  46806. }
  46807. m = p.x < p.next.x ? p : p.next;
  46808. }
  46809. }
  46810. p = p.next;
  46811. } while (p !== outerNode);
  46812. if (!m)
  46813. return null;
  46814. if (hx === qx)
  46815. return m.prev; // hole touches outer segment; pick lower endpoint
  46816. // look for points inside the triangle of hole point, segment intersection and endpoint;
  46817. // if there are no points found, we have a valid connection;
  46818. // otherwise choose the point of the minimum angle with the ray as connection point
  46819. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  46820. p = m.next;
  46821. while (p !== stop) {
  46822. if (hx >= p.x &&
  46823. p.x >= mx &&
  46824. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  46825. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  46826. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  46827. m = p;
  46828. tanMin = tan;
  46829. }
  46830. }
  46831. p = p.next;
  46832. }
  46833. return m;
  46834. }
  46835. // interlink polygon nodes in z-order
  46836. function indexCurve(start, minX, minY, size) {
  46837. var p = start;
  46838. do {
  46839. if (p.z === null)
  46840. p.z = zOrder(p.x, p.y, minX, minY, size);
  46841. p.prevZ = p.prev;
  46842. p.nextZ = p.next;
  46843. p = p.next;
  46844. } while (p !== start);
  46845. p.prevZ.nextZ = null;
  46846. p.prevZ = null;
  46847. sortLinked(p);
  46848. }
  46849. // Simon Tatham's linked list merge sort algorithm
  46850. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  46851. function sortLinked(list) {
  46852. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  46853. do {
  46854. p = list;
  46855. list = null;
  46856. tail = null;
  46857. numMerges = 0;
  46858. while (p) {
  46859. numMerges++;
  46860. q = p;
  46861. pSize = 0;
  46862. for (i = 0; i < inSize; i++) {
  46863. pSize++;
  46864. q = q.nextZ;
  46865. if (!q)
  46866. break;
  46867. }
  46868. qSize = inSize;
  46869. while (pSize > 0 || (qSize > 0 && q)) {
  46870. if (pSize === 0) {
  46871. e = q;
  46872. q = q.nextZ;
  46873. qSize--;
  46874. }
  46875. else if (qSize === 0 || !q) {
  46876. e = p;
  46877. p = p.nextZ;
  46878. pSize--;
  46879. }
  46880. else if (p.z <= q.z) {
  46881. e = p;
  46882. p = p.nextZ;
  46883. pSize--;
  46884. }
  46885. else {
  46886. e = q;
  46887. q = q.nextZ;
  46888. qSize--;
  46889. }
  46890. if (tail)
  46891. tail.nextZ = e;
  46892. else
  46893. list = e;
  46894. e.prevZ = tail;
  46895. tail = e;
  46896. }
  46897. p = q;
  46898. }
  46899. tail.nextZ = null;
  46900. inSize *= 2;
  46901. } while (numMerges > 1);
  46902. return list;
  46903. }
  46904. // z-order of a point given coords and size of the data bounding box
  46905. function zOrder(x, y, minX, minY, size) {
  46906. // coords are transformed into non-negative 15-bit integer range
  46907. x = 32767 * (x - minX) / size;
  46908. y = 32767 * (y - minY) / size;
  46909. x = (x | (x << 8)) & 0x00FF00FF;
  46910. x = (x | (x << 4)) & 0x0F0F0F0F;
  46911. x = (x | (x << 2)) & 0x33333333;
  46912. x = (x | (x << 1)) & 0x55555555;
  46913. y = (y | (y << 8)) & 0x00FF00FF;
  46914. y = (y | (y << 4)) & 0x0F0F0F0F;
  46915. y = (y | (y << 2)) & 0x33333333;
  46916. y = (y | (y << 1)) & 0x55555555;
  46917. return x | (y << 1);
  46918. }
  46919. // find the leftmost node of a polygon ring
  46920. function getLeftmost(start) {
  46921. var p = start, leftmost = start;
  46922. do {
  46923. if (p.x < leftmost.x)
  46924. leftmost = p;
  46925. p = p.next;
  46926. } while (p !== start);
  46927. return leftmost;
  46928. }
  46929. // check if a point lies within a convex triangle
  46930. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  46931. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  46932. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  46933. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  46934. }
  46935. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  46936. function isValidDiagonal(a, b) {
  46937. return a.next.i !== b.i &&
  46938. a.prev.i !== b.i &&
  46939. !intersectsPolygon(a, b) &&
  46940. locallyInside(a, b) &&
  46941. locallyInside(b, a) &&
  46942. middleInside(a, b);
  46943. }
  46944. // signed area of a triangle
  46945. function area(p, q, r) {
  46946. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  46947. }
  46948. // check if two points are equal
  46949. function equals(p1, p2) {
  46950. return p1.x === p2.x && p1.y === p2.y;
  46951. }
  46952. // check if two segments intersect
  46953. function intersects(p1, q1, p2, q2) {
  46954. if ((equals(p1, q1) && equals(p2, q2)) ||
  46955. (equals(p1, q2) && equals(p2, q1)))
  46956. return true;
  46957. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  46958. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  46959. }
  46960. // check if a polygon diagonal intersects any polygon segments
  46961. function intersectsPolygon(a, b) {
  46962. var p = a;
  46963. do {
  46964. if (p.i !== a.i &&
  46965. p.next.i !== a.i &&
  46966. p.i !== b.i &&
  46967. p.next.i !== b.i &&
  46968. intersects(p, p.next, a, b))
  46969. return true;
  46970. p = p.next;
  46971. } while (p !== a);
  46972. return false;
  46973. }
  46974. // check if a polygon diagonal is locally inside the polygon
  46975. function locallyInside(a, b) {
  46976. return area(a.prev, a, a.next) < 0
  46977. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  46978. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  46979. }
  46980. // check if the middle point of a polygon diagonal is inside the polygon
  46981. function middleInside(a, b) {
  46982. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  46983. do {
  46984. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  46985. inside = !inside;
  46986. p = p.next;
  46987. } while (p !== a);
  46988. return inside;
  46989. }
  46990. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  46991. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  46992. function splitPolygon(a, b) {
  46993. 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;
  46994. a.next = b;
  46995. b.prev = a;
  46996. a2.next = an;
  46997. an.prev = a2;
  46998. b2.next = a2;
  46999. a2.prev = b2;
  47000. bp.next = b2;
  47001. b2.prev = bp;
  47002. return b2;
  47003. }
  47004. // create a node and optionally link it with previous one (in a circular doubly linked list)
  47005. function insertNode(i, x, y, last) {
  47006. var p = new Node(i, x, y);
  47007. if (!last) {
  47008. p.prev = p;
  47009. p.next = p;
  47010. }
  47011. else {
  47012. p.next = last.next;
  47013. p.prev = last;
  47014. last.next.prev = p;
  47015. last.next = p;
  47016. }
  47017. return p;
  47018. }
  47019. function removeNode(p) {
  47020. p.next.prev = p.prev;
  47021. p.prev.next = p.next;
  47022. if (p.prevZ)
  47023. p.prevZ.nextZ = p.nextZ;
  47024. if (p.nextZ)
  47025. p.nextZ.prevZ = p.prevZ;
  47026. }
  47027. function Node(i, x, y) {
  47028. // vertice index in coordinates array
  47029. this.i = i;
  47030. // vertex coordinates
  47031. this.x = x;
  47032. this.y = y;
  47033. // previous and next vertice nodes in a polygon ring
  47034. this.prev = null;
  47035. this.next = null;
  47036. // z-order curve value
  47037. this.z = null;
  47038. // previous and next nodes in z-order
  47039. this.prevZ = null;
  47040. this.nextZ = null;
  47041. // indicates whether this is a steiner point
  47042. this.steiner = false;
  47043. }
  47044. /**
  47045. * return a percentage difference between the polygon area and its triangulation area;
  47046. * used to verify correctness of triangulation
  47047. */
  47048. function deviation(data, holeIndices, dim, triangles) {
  47049. var hasHoles = holeIndices && holeIndices.length;
  47050. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  47051. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  47052. if (hasHoles) {
  47053. for (var i = 0, len = holeIndices.length; i < len; i++) {
  47054. var start = holeIndices[i] * dim;
  47055. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47056. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  47057. }
  47058. }
  47059. var trianglesArea = 0;
  47060. for (i = 0; i < triangles.length; i += 3) {
  47061. var a = triangles[i] * dim;
  47062. var b = triangles[i + 1] * dim;
  47063. var c = triangles[i + 2] * dim;
  47064. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  47065. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  47066. }
  47067. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  47068. }
  47069. Earcut.deviation = deviation;
  47070. ;
  47071. function signedArea(data, start, end, dim) {
  47072. var sum = 0;
  47073. for (var i = start, j = end - dim; i < end; i += dim) {
  47074. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  47075. j = i;
  47076. }
  47077. return sum;
  47078. }
  47079. /**
  47080. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  47081. */
  47082. function flatten(data) {
  47083. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  47084. for (var i = 0; i < data.length; i++) {
  47085. for (var j = 0; j < data[i].length; j++) {
  47086. for (var d = 0; d < dim; d++)
  47087. result.vertices.push(data[i][j][d]);
  47088. }
  47089. if (i > 0) {
  47090. holeIndex += data[i - 1].length;
  47091. result.holes.push(holeIndex);
  47092. }
  47093. }
  47094. return result;
  47095. }
  47096. Earcut.flatten = flatten;
  47097. ;
  47098. })(Earcut || (Earcut = {}));
  47099. //# sourceMappingURL=babylon.earcut.js.map
  47100. var BABYLON;
  47101. (function (BABYLON) {
  47102. // Unique ID when we import meshes from Babylon to CSG
  47103. var currentCSGMeshId = 0;
  47104. // # class Vertex
  47105. // Represents a vertex of a polygon. Use your own vertex class instead of this
  47106. // one to provide additional features like texture coordinates and vertex
  47107. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  47108. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  47109. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  47110. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  47111. // is not used anywhere else.
  47112. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  47113. var Vertex = (function () {
  47114. function Vertex(pos, normal, uv) {
  47115. this.pos = pos;
  47116. this.normal = normal;
  47117. this.uv = uv;
  47118. }
  47119. Vertex.prototype.clone = function () {
  47120. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  47121. };
  47122. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  47123. // orientation of a polygon is flipped.
  47124. Vertex.prototype.flip = function () {
  47125. this.normal = this.normal.scale(-1);
  47126. };
  47127. // Create a new vertex between this vertex and `other` by linearly
  47128. // interpolating all properties using a parameter of `t`. Subclasses should
  47129. // override this to interpolate additional properties.
  47130. Vertex.prototype.interpolate = function (other, t) {
  47131. 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));
  47132. };
  47133. return Vertex;
  47134. }());
  47135. // # class Plane
  47136. // Represents a plane in 3D space.
  47137. var Plane = (function () {
  47138. function Plane(normal, w) {
  47139. this.normal = normal;
  47140. this.w = w;
  47141. }
  47142. Plane.FromPoints = function (a, b, c) {
  47143. var v0 = c.subtract(a);
  47144. var v1 = b.subtract(a);
  47145. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  47146. return null;
  47147. }
  47148. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  47149. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  47150. };
  47151. Plane.prototype.clone = function () {
  47152. return new Plane(this.normal.clone(), this.w);
  47153. };
  47154. Plane.prototype.flip = function () {
  47155. this.normal.scaleInPlace(-1);
  47156. this.w = -this.w;
  47157. };
  47158. // Split `polygon` by this plane if needed, then put the polygon or polygon
  47159. // fragments in the appropriate lists. Coplanar polygons go into either
  47160. // `coplanarFront` or `coplanarBack` depending on their orientation with
  47161. // respect to this plane. Polygons in front or in back of this plane go into
  47162. // either `front` or `back`.
  47163. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  47164. var COPLANAR = 0;
  47165. var FRONT = 1;
  47166. var BACK = 2;
  47167. var SPANNING = 3;
  47168. // Classify each point as well as the entire polygon into one of the above
  47169. // four classes.
  47170. var polygonType = 0;
  47171. var types = [];
  47172. var i;
  47173. var t;
  47174. for (i = 0; i < polygon.vertices.length; i++) {
  47175. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  47176. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  47177. polygonType |= type;
  47178. types.push(type);
  47179. }
  47180. // Put the polygon in the correct list, splitting it when necessary.
  47181. switch (polygonType) {
  47182. case COPLANAR:
  47183. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  47184. break;
  47185. case FRONT:
  47186. front.push(polygon);
  47187. break;
  47188. case BACK:
  47189. back.push(polygon);
  47190. break;
  47191. case SPANNING:
  47192. var f = [], b = [];
  47193. for (i = 0; i < polygon.vertices.length; i++) {
  47194. var j = (i + 1) % polygon.vertices.length;
  47195. var ti = types[i], tj = types[j];
  47196. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  47197. if (ti !== BACK)
  47198. f.push(vi);
  47199. if (ti !== FRONT)
  47200. b.push(ti !== BACK ? vi.clone() : vi);
  47201. if ((ti | tj) === SPANNING) {
  47202. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  47203. var v = vi.interpolate(vj, t);
  47204. f.push(v);
  47205. b.push(v.clone());
  47206. }
  47207. }
  47208. var poly;
  47209. if (f.length >= 3) {
  47210. poly = new Polygon(f, polygon.shared);
  47211. if (poly.plane)
  47212. front.push(poly);
  47213. }
  47214. if (b.length >= 3) {
  47215. poly = new Polygon(b, polygon.shared);
  47216. if (poly.plane)
  47217. back.push(poly);
  47218. }
  47219. break;
  47220. }
  47221. };
  47222. return Plane;
  47223. }());
  47224. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  47225. // point is on the plane.
  47226. Plane.EPSILON = 1e-5;
  47227. // # class Polygon
  47228. // Represents a convex polygon. The vertices used to initialize a polygon must
  47229. // be coplanar and form a convex loop.
  47230. //
  47231. // Each convex polygon has a `shared` property, which is shared between all
  47232. // polygons that are clones of each other or were split from the same polygon.
  47233. // This can be used to define per-polygon properties (such as surface color).
  47234. var Polygon = (function () {
  47235. function Polygon(vertices, shared) {
  47236. this.vertices = vertices;
  47237. this.shared = shared;
  47238. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  47239. }
  47240. Polygon.prototype.clone = function () {
  47241. var vertices = this.vertices.map(function (v) { return v.clone(); });
  47242. return new Polygon(vertices, this.shared);
  47243. };
  47244. Polygon.prototype.flip = function () {
  47245. this.vertices.reverse().map(function (v) { v.flip(); });
  47246. this.plane.flip();
  47247. };
  47248. return Polygon;
  47249. }());
  47250. // # class Node
  47251. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  47252. // by picking a polygon to split along. That polygon (and all other coplanar
  47253. // polygons) are added directly to that node and the other polygons are added to
  47254. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  47255. // no distinction between internal and leaf nodes.
  47256. var Node = (function () {
  47257. function Node(polygons) {
  47258. this.plane = null;
  47259. this.front = null;
  47260. this.back = null;
  47261. this.polygons = [];
  47262. if (polygons) {
  47263. this.build(polygons);
  47264. }
  47265. }
  47266. Node.prototype.clone = function () {
  47267. var node = new Node();
  47268. node.plane = this.plane && this.plane.clone();
  47269. node.front = this.front && this.front.clone();
  47270. node.back = this.back && this.back.clone();
  47271. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  47272. return node;
  47273. };
  47274. // Convert solid space to empty space and empty space to solid space.
  47275. Node.prototype.invert = function () {
  47276. for (var i = 0; i < this.polygons.length; i++) {
  47277. this.polygons[i].flip();
  47278. }
  47279. if (this.plane) {
  47280. this.plane.flip();
  47281. }
  47282. if (this.front) {
  47283. this.front.invert();
  47284. }
  47285. if (this.back) {
  47286. this.back.invert();
  47287. }
  47288. var temp = this.front;
  47289. this.front = this.back;
  47290. this.back = temp;
  47291. };
  47292. // Recursively remove all polygons in `polygons` that are inside this BSP
  47293. // tree.
  47294. Node.prototype.clipPolygons = function (polygons) {
  47295. if (!this.plane)
  47296. return polygons.slice();
  47297. var front = [], back = [];
  47298. for (var i = 0; i < polygons.length; i++) {
  47299. this.plane.splitPolygon(polygons[i], front, back, front, back);
  47300. }
  47301. if (this.front) {
  47302. front = this.front.clipPolygons(front);
  47303. }
  47304. if (this.back) {
  47305. back = this.back.clipPolygons(back);
  47306. }
  47307. else {
  47308. back = [];
  47309. }
  47310. return front.concat(back);
  47311. };
  47312. // Remove all polygons in this BSP tree that are inside the other BSP tree
  47313. // `bsp`.
  47314. Node.prototype.clipTo = function (bsp) {
  47315. this.polygons = bsp.clipPolygons(this.polygons);
  47316. if (this.front)
  47317. this.front.clipTo(bsp);
  47318. if (this.back)
  47319. this.back.clipTo(bsp);
  47320. };
  47321. // Return a list of all polygons in this BSP tree.
  47322. Node.prototype.allPolygons = function () {
  47323. var polygons = this.polygons.slice();
  47324. if (this.front)
  47325. polygons = polygons.concat(this.front.allPolygons());
  47326. if (this.back)
  47327. polygons = polygons.concat(this.back.allPolygons());
  47328. return polygons;
  47329. };
  47330. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  47331. // new polygons are filtered down to the bottom of the tree and become new
  47332. // nodes there. Each set of polygons is partitioned using the first polygon
  47333. // (no heuristic is used to pick a good split).
  47334. Node.prototype.build = function (polygons) {
  47335. if (!polygons.length)
  47336. return;
  47337. if (!this.plane)
  47338. this.plane = polygons[0].plane.clone();
  47339. var front = [], back = [];
  47340. for (var i = 0; i < polygons.length; i++) {
  47341. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  47342. }
  47343. if (front.length) {
  47344. if (!this.front)
  47345. this.front = new Node();
  47346. this.front.build(front);
  47347. }
  47348. if (back.length) {
  47349. if (!this.back)
  47350. this.back = new Node();
  47351. this.back.build(back);
  47352. }
  47353. };
  47354. return Node;
  47355. }());
  47356. var CSG = (function () {
  47357. function CSG() {
  47358. this.polygons = new Array();
  47359. }
  47360. // Convert BABYLON.Mesh to BABYLON.CSG
  47361. CSG.FromMesh = function (mesh) {
  47362. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  47363. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  47364. if (mesh instanceof BABYLON.Mesh) {
  47365. mesh.computeWorldMatrix(true);
  47366. matrix = mesh.getWorldMatrix();
  47367. meshPosition = mesh.position.clone();
  47368. meshRotation = mesh.rotation.clone();
  47369. if (mesh.rotationQuaternion) {
  47370. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  47371. }
  47372. meshScaling = mesh.scaling.clone();
  47373. }
  47374. else {
  47375. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  47376. }
  47377. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47378. var subMeshes = mesh.subMeshes;
  47379. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  47380. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  47381. vertices = [];
  47382. for (var j = 0; j < 3; j++) {
  47383. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  47384. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  47385. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  47386. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  47387. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  47388. vertex = new Vertex(position, normal, uv);
  47389. vertices.push(vertex);
  47390. }
  47391. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  47392. // To handle the case of degenerated triangle
  47393. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  47394. if (polygon.plane)
  47395. polygons.push(polygon);
  47396. }
  47397. }
  47398. var csg = CSG.FromPolygons(polygons);
  47399. csg.matrix = matrix;
  47400. csg.position = meshPosition;
  47401. csg.rotation = meshRotation;
  47402. csg.scaling = meshScaling;
  47403. csg.rotationQuaternion = meshRotationQuaternion;
  47404. currentCSGMeshId++;
  47405. return csg;
  47406. };
  47407. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  47408. CSG.FromPolygons = function (polygons) {
  47409. var csg = new CSG();
  47410. csg.polygons = polygons;
  47411. return csg;
  47412. };
  47413. CSG.prototype.clone = function () {
  47414. var csg = new CSG();
  47415. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  47416. csg.copyTransformAttributes(this);
  47417. return csg;
  47418. };
  47419. CSG.prototype.toPolygons = function () {
  47420. return this.polygons;
  47421. };
  47422. CSG.prototype.union = function (csg) {
  47423. var a = new Node(this.clone().polygons);
  47424. var b = new Node(csg.clone().polygons);
  47425. a.clipTo(b);
  47426. b.clipTo(a);
  47427. b.invert();
  47428. b.clipTo(a);
  47429. b.invert();
  47430. a.build(b.allPolygons());
  47431. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  47432. };
  47433. CSG.prototype.unionInPlace = function (csg) {
  47434. var a = new Node(this.polygons);
  47435. var b = new Node(csg.polygons);
  47436. a.clipTo(b);
  47437. b.clipTo(a);
  47438. b.invert();
  47439. b.clipTo(a);
  47440. b.invert();
  47441. a.build(b.allPolygons());
  47442. this.polygons = a.allPolygons();
  47443. };
  47444. CSG.prototype.subtract = function (csg) {
  47445. var a = new Node(this.clone().polygons);
  47446. var b = new Node(csg.clone().polygons);
  47447. a.invert();
  47448. a.clipTo(b);
  47449. b.clipTo(a);
  47450. b.invert();
  47451. b.clipTo(a);
  47452. b.invert();
  47453. a.build(b.allPolygons());
  47454. a.invert();
  47455. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  47456. };
  47457. CSG.prototype.subtractInPlace = function (csg) {
  47458. var a = new Node(this.polygons);
  47459. var b = new Node(csg.polygons);
  47460. a.invert();
  47461. a.clipTo(b);
  47462. b.clipTo(a);
  47463. b.invert();
  47464. b.clipTo(a);
  47465. b.invert();
  47466. a.build(b.allPolygons());
  47467. a.invert();
  47468. this.polygons = a.allPolygons();
  47469. };
  47470. CSG.prototype.intersect = function (csg) {
  47471. var a = new Node(this.clone().polygons);
  47472. var b = new Node(csg.clone().polygons);
  47473. a.invert();
  47474. b.clipTo(a);
  47475. b.invert();
  47476. a.clipTo(b);
  47477. b.clipTo(a);
  47478. a.build(b.allPolygons());
  47479. a.invert();
  47480. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  47481. };
  47482. CSG.prototype.intersectInPlace = function (csg) {
  47483. var a = new Node(this.polygons);
  47484. var b = new Node(csg.polygons);
  47485. a.invert();
  47486. b.clipTo(a);
  47487. b.invert();
  47488. a.clipTo(b);
  47489. b.clipTo(a);
  47490. a.build(b.allPolygons());
  47491. a.invert();
  47492. this.polygons = a.allPolygons();
  47493. };
  47494. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  47495. // not modified.
  47496. CSG.prototype.inverse = function () {
  47497. var csg = this.clone();
  47498. csg.inverseInPlace();
  47499. return csg;
  47500. };
  47501. CSG.prototype.inverseInPlace = function () {
  47502. this.polygons.map(function (p) { p.flip(); });
  47503. };
  47504. // This is used to keep meshes transformations so they can be restored
  47505. // when we build back a Babylon Mesh
  47506. // NB : All CSG operations are performed in world coordinates
  47507. CSG.prototype.copyTransformAttributes = function (csg) {
  47508. this.matrix = csg.matrix;
  47509. this.position = csg.position;
  47510. this.rotation = csg.rotation;
  47511. this.scaling = csg.scaling;
  47512. this.rotationQuaternion = csg.rotationQuaternion;
  47513. return this;
  47514. };
  47515. // Build Raw mesh from CSG
  47516. // Coordinates here are in world space
  47517. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  47518. var matrix = this.matrix.clone();
  47519. matrix.invert();
  47520. 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;
  47521. if (keepSubMeshes) {
  47522. // Sort Polygons, since subMeshes are indices range
  47523. polygons.sort(function (a, b) {
  47524. if (a.shared.meshId === b.shared.meshId) {
  47525. return a.shared.subMeshId - b.shared.subMeshId;
  47526. }
  47527. else {
  47528. return a.shared.meshId - b.shared.meshId;
  47529. }
  47530. });
  47531. }
  47532. for (var i = 0, il = polygons.length; i < il; i++) {
  47533. polygon = polygons[i];
  47534. // Building SubMeshes
  47535. if (!subMesh_dict[polygon.shared.meshId]) {
  47536. subMesh_dict[polygon.shared.meshId] = {};
  47537. }
  47538. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  47539. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  47540. indexStart: +Infinity,
  47541. indexEnd: -Infinity,
  47542. materialIndex: polygon.shared.materialIndex
  47543. };
  47544. }
  47545. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  47546. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  47547. polygonIndices[0] = 0;
  47548. polygonIndices[1] = j - 1;
  47549. polygonIndices[2] = j;
  47550. for (var k = 0; k < 3; k++) {
  47551. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  47552. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  47553. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  47554. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  47555. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  47556. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  47557. // Check if 2 points can be merged
  47558. if (!(typeof vertex_idx !== 'undefined' &&
  47559. normals[vertex_idx * 3] === localNormal.x &&
  47560. normals[vertex_idx * 3 + 1] === localNormal.y &&
  47561. normals[vertex_idx * 3 + 2] === localNormal.z &&
  47562. uvs[vertex_idx * 2] === uv.x &&
  47563. uvs[vertex_idx * 2 + 1] === uv.y)) {
  47564. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  47565. uvs.push(uv.x, uv.y);
  47566. normals.push(normal.x, normal.y, normal.z);
  47567. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  47568. }
  47569. indices.push(vertex_idx);
  47570. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  47571. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  47572. currentIndex++;
  47573. }
  47574. }
  47575. }
  47576. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  47577. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  47578. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  47579. mesh.setIndices(indices);
  47580. if (keepSubMeshes) {
  47581. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  47582. var materialIndexOffset = 0, materialMaxIndex;
  47583. mesh.subMeshes = new Array();
  47584. for (var m in subMesh_dict) {
  47585. materialMaxIndex = -1;
  47586. for (var sm in subMesh_dict[m]) {
  47587. subMesh_obj = subMesh_dict[m][sm];
  47588. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  47589. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  47590. }
  47591. materialIndexOffset += ++materialMaxIndex;
  47592. }
  47593. }
  47594. return mesh;
  47595. };
  47596. // Build Mesh from CSG taking material and transforms into account
  47597. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  47598. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  47599. mesh.material = material;
  47600. mesh.position.copyFrom(this.position);
  47601. mesh.rotation.copyFrom(this.rotation);
  47602. if (this.rotationQuaternion) {
  47603. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  47604. }
  47605. mesh.scaling.copyFrom(this.scaling);
  47606. mesh.computeWorldMatrix(true);
  47607. return mesh;
  47608. };
  47609. return CSG;
  47610. }());
  47611. BABYLON.CSG = CSG;
  47612. })(BABYLON || (BABYLON = {}));
  47613. //# sourceMappingURL=babylon.csg.js.map
  47614. var BABYLON;
  47615. (function (BABYLON) {
  47616. var VRDistortionCorrectionPostProcess = (function (_super) {
  47617. __extends(VRDistortionCorrectionPostProcess, _super);
  47618. //ANY
  47619. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  47620. var _this = _super.call(this, name, "vrDistortionCorrection", [
  47621. 'LensCenter',
  47622. 'Scale',
  47623. 'ScaleIn',
  47624. 'HmdWarpParam'
  47625. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  47626. _this._isRightEye = isRightEye;
  47627. _this._distortionFactors = vrMetrics.distortionK;
  47628. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  47629. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  47630. _this.onSizeChangedObservable.add(function () {
  47631. _this.aspectRatio = _this.width * .5 / _this.height;
  47632. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  47633. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  47634. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  47635. });
  47636. _this.onApplyObservable.add(function (effect) {
  47637. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  47638. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  47639. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  47640. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  47641. });
  47642. return _this;
  47643. }
  47644. return VRDistortionCorrectionPostProcess;
  47645. }(BABYLON.PostProcess));
  47646. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  47647. })(BABYLON || (BABYLON = {}));
  47648. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  47649. // Mainly based on these 2 articles :
  47650. // 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
  47651. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  47652. var BABYLON;
  47653. (function (BABYLON) {
  47654. var JoystickAxis;
  47655. (function (JoystickAxis) {
  47656. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  47657. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  47658. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  47659. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  47660. var VirtualJoystick = (function () {
  47661. function VirtualJoystick(leftJoystick) {
  47662. var _this = this;
  47663. if (leftJoystick) {
  47664. this._leftJoystick = true;
  47665. }
  47666. else {
  47667. this._leftJoystick = false;
  47668. }
  47669. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  47670. VirtualJoystick._globalJoystickIndex++;
  47671. // By default left & right arrow keys are moving the X
  47672. // and up & down keys are moving the Y
  47673. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47674. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47675. this.reverseLeftRight = false;
  47676. this.reverseUpDown = false;
  47677. // collections of pointers
  47678. this._touches = new BABYLON.StringDictionary();
  47679. this.deltaPosition = BABYLON.Vector3.Zero();
  47680. this._joystickSensibility = 25;
  47681. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47682. this._rotationSpeed = 25;
  47683. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  47684. this._rotateOnAxisRelativeToMesh = false;
  47685. this._onResize = function (evt) {
  47686. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47687. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47688. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  47689. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  47690. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  47691. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  47692. };
  47693. // injecting a canvas element on top of the canvas 3D game
  47694. if (!VirtualJoystick.vjCanvas) {
  47695. window.addEventListener("resize", this._onResize, false);
  47696. VirtualJoystick.vjCanvas = document.createElement("canvas");
  47697. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  47698. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  47699. VirtualJoystick.vjCanvas.width = window.innerWidth;
  47700. VirtualJoystick.vjCanvas.height = window.innerHeight;
  47701. VirtualJoystick.vjCanvas.style.width = "100%";
  47702. VirtualJoystick.vjCanvas.style.height = "100%";
  47703. VirtualJoystick.vjCanvas.style.position = "absolute";
  47704. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  47705. VirtualJoystick.vjCanvas.style.top = "0px";
  47706. VirtualJoystick.vjCanvas.style.left = "0px";
  47707. VirtualJoystick.vjCanvas.style.zIndex = "5";
  47708. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  47709. // Support for jQuery PEP polyfill
  47710. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  47711. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  47712. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  47713. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47714. document.body.appendChild(VirtualJoystick.vjCanvas);
  47715. }
  47716. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  47717. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  47718. this.pressed = false;
  47719. // default joystick color
  47720. this._joystickColor = "cyan";
  47721. this._joystickPointerID = -1;
  47722. // current joystick position
  47723. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  47724. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  47725. // origin joystick position
  47726. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  47727. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  47728. this._onPointerDownHandlerRef = function (evt) {
  47729. _this._onPointerDown(evt);
  47730. };
  47731. this._onPointerMoveHandlerRef = function (evt) {
  47732. _this._onPointerMove(evt);
  47733. };
  47734. this._onPointerOutHandlerRef = function (evt) {
  47735. _this._onPointerUp(evt);
  47736. };
  47737. this._onPointerUpHandlerRef = function (evt) {
  47738. _this._onPointerUp(evt);
  47739. };
  47740. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  47741. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  47742. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  47743. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  47744. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  47745. evt.preventDefault(); // Disables system menu
  47746. }, false);
  47747. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47748. }
  47749. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  47750. this._joystickSensibility = newJoystickSensibility;
  47751. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  47752. };
  47753. VirtualJoystick.prototype._onPointerDown = function (e) {
  47754. var positionOnScreenCondition;
  47755. e.preventDefault();
  47756. if (this._leftJoystick === true) {
  47757. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  47758. }
  47759. else {
  47760. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  47761. }
  47762. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  47763. // First contact will be dedicated to the virtual joystick
  47764. this._joystickPointerID = e.pointerId;
  47765. this._joystickPointerStartPos.x = e.clientX;
  47766. this._joystickPointerStartPos.y = e.clientY;
  47767. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  47768. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  47769. this._deltaJoystickVector.x = 0;
  47770. this._deltaJoystickVector.y = 0;
  47771. this.pressed = true;
  47772. this._touches.add(e.pointerId.toString(), e);
  47773. }
  47774. else {
  47775. // You can only trigger the action buttons with a joystick declared
  47776. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  47777. this._action();
  47778. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  47779. }
  47780. }
  47781. };
  47782. VirtualJoystick.prototype._onPointerMove = function (e) {
  47783. // If the current pointer is the one associated to the joystick (first touch contact)
  47784. if (this._joystickPointerID == e.pointerId) {
  47785. this._joystickPointerPos.x = e.clientX;
  47786. this._joystickPointerPos.y = e.clientY;
  47787. this._deltaJoystickVector = this._joystickPointerPos.clone();
  47788. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  47789. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  47790. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  47791. switch (this._axisTargetedByLeftAndRight) {
  47792. case JoystickAxis.X:
  47793. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  47794. break;
  47795. case JoystickAxis.Y:
  47796. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  47797. break;
  47798. case JoystickAxis.Z:
  47799. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  47800. break;
  47801. }
  47802. var directionUpDown = this.reverseUpDown ? 1 : -1;
  47803. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  47804. switch (this._axisTargetedByUpAndDown) {
  47805. case JoystickAxis.X:
  47806. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  47807. break;
  47808. case JoystickAxis.Y:
  47809. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  47810. break;
  47811. case JoystickAxis.Z:
  47812. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  47813. break;
  47814. }
  47815. }
  47816. else {
  47817. var data = this._touches.get(e.pointerId.toString());
  47818. if (data) {
  47819. data.x = e.clientX;
  47820. data.y = e.clientY;
  47821. }
  47822. }
  47823. };
  47824. VirtualJoystick.prototype._onPointerUp = function (e) {
  47825. if (this._joystickPointerID == e.pointerId) {
  47826. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  47827. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  47828. this._joystickPointerID = -1;
  47829. this.pressed = false;
  47830. }
  47831. else {
  47832. var touch = this._touches.get(e.pointerId.toString());
  47833. if (touch) {
  47834. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47835. }
  47836. }
  47837. this._deltaJoystickVector.x = 0;
  47838. this._deltaJoystickVector.y = 0;
  47839. this._touches.remove(e.pointerId.toString());
  47840. };
  47841. /**
  47842. * Change the color of the virtual joystick
  47843. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  47844. */
  47845. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  47846. this._joystickColor = newColor;
  47847. };
  47848. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  47849. this._action = action;
  47850. };
  47851. // Define which axis you'd like to control for left & right
  47852. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  47853. switch (axis) {
  47854. case JoystickAxis.X:
  47855. case JoystickAxis.Y:
  47856. case JoystickAxis.Z:
  47857. this._axisTargetedByLeftAndRight = axis;
  47858. break;
  47859. default:
  47860. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  47861. break;
  47862. }
  47863. };
  47864. // Define which axis you'd like to control for up & down
  47865. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  47866. switch (axis) {
  47867. case JoystickAxis.X:
  47868. case JoystickAxis.Y:
  47869. case JoystickAxis.Z:
  47870. this._axisTargetedByUpAndDown = axis;
  47871. break;
  47872. default:
  47873. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  47874. break;
  47875. }
  47876. };
  47877. VirtualJoystick.prototype._clearCanvas = function () {
  47878. if (this._leftJoystick) {
  47879. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  47880. }
  47881. else {
  47882. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  47883. }
  47884. };
  47885. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  47886. var _this = this;
  47887. if (this.pressed) {
  47888. this._touches.forEach(function (key, touch) {
  47889. if (touch.pointerId === _this._joystickPointerID) {
  47890. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  47891. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  47892. VirtualJoystick.vjCanvasContext.beginPath();
  47893. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47894. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47895. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  47896. VirtualJoystick.vjCanvasContext.stroke();
  47897. VirtualJoystick.vjCanvasContext.closePath();
  47898. VirtualJoystick.vjCanvasContext.beginPath();
  47899. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47900. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  47901. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  47902. VirtualJoystick.vjCanvasContext.stroke();
  47903. VirtualJoystick.vjCanvasContext.closePath();
  47904. VirtualJoystick.vjCanvasContext.beginPath();
  47905. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  47906. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  47907. VirtualJoystick.vjCanvasContext.stroke();
  47908. VirtualJoystick.vjCanvasContext.closePath();
  47909. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  47910. }
  47911. else {
  47912. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  47913. VirtualJoystick.vjCanvasContext.beginPath();
  47914. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  47915. VirtualJoystick.vjCanvasContext.beginPath();
  47916. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  47917. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  47918. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  47919. VirtualJoystick.vjCanvasContext.stroke();
  47920. VirtualJoystick.vjCanvasContext.closePath();
  47921. touch.prevX = touch.x;
  47922. touch.prevY = touch.y;
  47923. }
  47924. ;
  47925. });
  47926. }
  47927. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  47928. };
  47929. VirtualJoystick.prototype.releaseCanvas = function () {
  47930. if (VirtualJoystick.vjCanvas) {
  47931. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  47932. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  47933. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  47934. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  47935. window.removeEventListener("resize", this._onResize);
  47936. document.body.removeChild(VirtualJoystick.vjCanvas);
  47937. VirtualJoystick.vjCanvas = null;
  47938. }
  47939. };
  47940. return VirtualJoystick;
  47941. }());
  47942. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  47943. VirtualJoystick._globalJoystickIndex = 0;
  47944. BABYLON.VirtualJoystick = VirtualJoystick;
  47945. })(BABYLON || (BABYLON = {}));
  47946. //# sourceMappingURL=babylon.virtualJoystick.js.map
  47947. var BABYLON;
  47948. (function (BABYLON) {
  47949. // We're mainly based on the logic defined into the FreeCamera code
  47950. var VirtualJoysticksCamera = (function (_super) {
  47951. __extends(VirtualJoysticksCamera, _super);
  47952. function VirtualJoysticksCamera(name, position, scene) {
  47953. var _this = _super.call(this, name, position, scene) || this;
  47954. _this.inputs.addVirtualJoystick();
  47955. return _this;
  47956. }
  47957. VirtualJoysticksCamera.prototype.getClassName = function () {
  47958. return "VirtualJoysticksCamera";
  47959. };
  47960. return VirtualJoysticksCamera;
  47961. }(BABYLON.FreeCamera));
  47962. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  47963. })(BABYLON || (BABYLON = {}));
  47964. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  47965. var BABYLON;
  47966. (function (BABYLON) {
  47967. var FreeCameraVirtualJoystickInput = (function () {
  47968. function FreeCameraVirtualJoystickInput() {
  47969. }
  47970. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  47971. return this._leftjoystick;
  47972. };
  47973. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  47974. return this._rightjoystick;
  47975. };
  47976. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  47977. if (this._leftjoystick) {
  47978. var camera = this.camera;
  47979. var speed = camera._computeLocalCameraSpeed() * 50;
  47980. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  47981. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  47982. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  47983. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  47984. if (!this._leftjoystick.pressed) {
  47985. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  47986. }
  47987. if (!this._rightjoystick.pressed) {
  47988. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  47989. }
  47990. }
  47991. };
  47992. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  47993. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  47994. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  47995. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  47996. this._leftjoystick.setJoystickSensibility(0.15);
  47997. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  47998. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  47999. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48000. this._rightjoystick.reverseUpDown = true;
  48001. this._rightjoystick.setJoystickSensibility(0.05);
  48002. this._rightjoystick.setJoystickColor("yellow");
  48003. };
  48004. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48005. this._leftjoystick.releaseCanvas();
  48006. this._rightjoystick.releaseCanvas();
  48007. };
  48008. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48009. return "FreeCameraVirtualJoystickInput";
  48010. };
  48011. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  48012. return "virtualJoystick";
  48013. };
  48014. return FreeCameraVirtualJoystickInput;
  48015. }());
  48016. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  48017. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  48018. })(BABYLON || (BABYLON = {}));
  48019. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  48020. var BABYLON;
  48021. (function (BABYLON) {
  48022. var AnaglyphPostProcess = (function (_super) {
  48023. __extends(AnaglyphPostProcess, _super);
  48024. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  48025. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  48026. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48027. _this.onApplyObservable.add(function (effect) {
  48028. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  48029. });
  48030. return _this;
  48031. }
  48032. return AnaglyphPostProcess;
  48033. }(BABYLON.PostProcess));
  48034. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  48035. })(BABYLON || (BABYLON = {}));
  48036. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  48037. var BABYLON;
  48038. (function (BABYLON) {
  48039. var OutlineRenderer = (function () {
  48040. function OutlineRenderer(scene) {
  48041. this._scene = scene;
  48042. }
  48043. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  48044. var _this = this;
  48045. if (useOverlay === void 0) { useOverlay = false; }
  48046. var scene = this._scene;
  48047. var engine = this._scene.getEngine();
  48048. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48049. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  48050. return;
  48051. }
  48052. var mesh = subMesh.getRenderingMesh();
  48053. var material = subMesh.getMaterial();
  48054. engine.enableEffect(this._effect);
  48055. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  48056. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  48057. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48058. // Bones
  48059. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48060. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48061. }
  48062. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48063. // Alpha test
  48064. if (material && material.needAlphaTesting()) {
  48065. var alphaTexture = material.getAlphaTestTexture();
  48066. this._effect.setTexture("diffuseSampler", alphaTexture);
  48067. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48068. }
  48069. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  48070. };
  48071. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  48072. var defines = [];
  48073. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  48074. var mesh = subMesh.getMesh();
  48075. var material = subMesh.getMaterial();
  48076. // Alpha test
  48077. if (material && material.needAlphaTesting()) {
  48078. defines.push("#define ALPHATEST");
  48079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48080. attribs.push(BABYLON.VertexBuffer.UVKind);
  48081. defines.push("#define UV1");
  48082. }
  48083. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48084. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48085. defines.push("#define UV2");
  48086. }
  48087. }
  48088. // Bones
  48089. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48090. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48091. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48092. if (mesh.numBoneInfluencers > 4) {
  48093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48095. }
  48096. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48097. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48098. }
  48099. else {
  48100. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48101. }
  48102. // Instances
  48103. if (useInstances) {
  48104. defines.push("#define INSTANCES");
  48105. attribs.push("world0");
  48106. attribs.push("world1");
  48107. attribs.push("world2");
  48108. attribs.push("world3");
  48109. }
  48110. // Get correct effect
  48111. var join = defines.join("\n");
  48112. if (this._cachedDefines !== join) {
  48113. this._cachedDefines = join;
  48114. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  48115. }
  48116. return this._effect.isReady();
  48117. };
  48118. return OutlineRenderer;
  48119. }());
  48120. BABYLON.OutlineRenderer = OutlineRenderer;
  48121. })(BABYLON || (BABYLON = {}));
  48122. //# sourceMappingURL=babylon.outlineRenderer.js.map
  48123. var BABYLON;
  48124. (function (BABYLON) {
  48125. var MeshAssetTask = (function () {
  48126. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  48127. this.name = name;
  48128. this.meshesNames = meshesNames;
  48129. this.rootUrl = rootUrl;
  48130. this.sceneFilename = sceneFilename;
  48131. this.isCompleted = false;
  48132. }
  48133. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48134. var _this = this;
  48135. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  48136. _this.loadedMeshes = meshes;
  48137. _this.loadedParticleSystems = particleSystems;
  48138. _this.loadedSkeletons = skeletons;
  48139. _this.isCompleted = true;
  48140. if (_this.onSuccess) {
  48141. _this.onSuccess(_this);
  48142. }
  48143. onSuccess();
  48144. }, null, function () {
  48145. if (_this.onError) {
  48146. _this.onError(_this);
  48147. }
  48148. onError();
  48149. });
  48150. };
  48151. return MeshAssetTask;
  48152. }());
  48153. BABYLON.MeshAssetTask = MeshAssetTask;
  48154. var TextFileAssetTask = (function () {
  48155. function TextFileAssetTask(name, url) {
  48156. this.name = name;
  48157. this.url = url;
  48158. this.isCompleted = false;
  48159. }
  48160. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48161. var _this = this;
  48162. BABYLON.Tools.LoadFile(this.url, function (data) {
  48163. _this.text = data;
  48164. _this.isCompleted = true;
  48165. if (_this.onSuccess) {
  48166. _this.onSuccess(_this);
  48167. }
  48168. onSuccess();
  48169. }, null, scene.database, false, function () {
  48170. if (_this.onError) {
  48171. _this.onError(_this);
  48172. }
  48173. onError();
  48174. });
  48175. };
  48176. return TextFileAssetTask;
  48177. }());
  48178. BABYLON.TextFileAssetTask = TextFileAssetTask;
  48179. var BinaryFileAssetTask = (function () {
  48180. function BinaryFileAssetTask(name, url) {
  48181. this.name = name;
  48182. this.url = url;
  48183. this.isCompleted = false;
  48184. }
  48185. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48186. var _this = this;
  48187. BABYLON.Tools.LoadFile(this.url, function (data) {
  48188. _this.data = data;
  48189. _this.isCompleted = true;
  48190. if (_this.onSuccess) {
  48191. _this.onSuccess(_this);
  48192. }
  48193. onSuccess();
  48194. }, null, scene.database, true, function () {
  48195. if (_this.onError) {
  48196. _this.onError(_this);
  48197. }
  48198. onError();
  48199. });
  48200. };
  48201. return BinaryFileAssetTask;
  48202. }());
  48203. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  48204. var ImageAssetTask = (function () {
  48205. function ImageAssetTask(name, url) {
  48206. this.name = name;
  48207. this.url = url;
  48208. this.isCompleted = false;
  48209. }
  48210. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48211. var _this = this;
  48212. var img = new Image();
  48213. BABYLON.Tools.SetCorsBehavior(this.url, img);
  48214. img.onload = function () {
  48215. _this.image = img;
  48216. _this.isCompleted = true;
  48217. if (_this.onSuccess) {
  48218. _this.onSuccess(_this);
  48219. }
  48220. onSuccess();
  48221. };
  48222. img.onerror = function () {
  48223. if (_this.onError) {
  48224. _this.onError(_this);
  48225. }
  48226. onError();
  48227. };
  48228. img.src = this.url;
  48229. };
  48230. return ImageAssetTask;
  48231. }());
  48232. BABYLON.ImageAssetTask = ImageAssetTask;
  48233. var TextureAssetTask = (function () {
  48234. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  48235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48236. this.name = name;
  48237. this.url = url;
  48238. this.noMipmap = noMipmap;
  48239. this.invertY = invertY;
  48240. this.samplingMode = samplingMode;
  48241. this.isCompleted = false;
  48242. }
  48243. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48244. var _this = this;
  48245. var onload = function () {
  48246. _this.isCompleted = true;
  48247. if (_this.onSuccess) {
  48248. _this.onSuccess(_this);
  48249. }
  48250. onSuccess();
  48251. };
  48252. var onerror = function () {
  48253. if (_this.onError) {
  48254. _this.onError(_this);
  48255. }
  48256. onError();
  48257. };
  48258. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  48259. };
  48260. return TextureAssetTask;
  48261. }());
  48262. BABYLON.TextureAssetTask = TextureAssetTask;
  48263. var CubeTextureAssetTask = (function () {
  48264. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  48265. this.name = name;
  48266. this.url = url;
  48267. this.extensions = extensions;
  48268. this.noMipmap = noMipmap;
  48269. this.files = files;
  48270. this.isCompleted = false;
  48271. }
  48272. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48273. var _this = this;
  48274. var onload = function () {
  48275. _this.isCompleted = true;
  48276. if (_this.onSuccess) {
  48277. _this.onSuccess(_this);
  48278. }
  48279. onSuccess();
  48280. };
  48281. var onerror = function () {
  48282. if (_this.onError) {
  48283. _this.onError(_this);
  48284. }
  48285. onError();
  48286. };
  48287. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  48288. };
  48289. return CubeTextureAssetTask;
  48290. }());
  48291. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  48292. var HDRCubeTextureAssetTask = (function () {
  48293. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  48294. if (noMipmap === void 0) { noMipmap = false; }
  48295. if (generateHarmonics === void 0) { generateHarmonics = true; }
  48296. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  48297. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  48298. this.name = name;
  48299. this.url = url;
  48300. this.size = size;
  48301. this.noMipmap = noMipmap;
  48302. this.generateHarmonics = generateHarmonics;
  48303. this.useInGammaSpace = useInGammaSpace;
  48304. this.usePMREMGenerator = usePMREMGenerator;
  48305. this.isCompleted = false;
  48306. }
  48307. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48308. var _this = this;
  48309. var onload = function () {
  48310. _this.isCompleted = true;
  48311. if (_this.onSuccess) {
  48312. _this.onSuccess(_this);
  48313. }
  48314. onSuccess();
  48315. };
  48316. var onerror = function () {
  48317. if (_this.onError) {
  48318. _this.onError(_this);
  48319. }
  48320. onError();
  48321. };
  48322. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  48323. };
  48324. return HDRCubeTextureAssetTask;
  48325. }());
  48326. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  48327. var AssetsManager = (function () {
  48328. function AssetsManager(scene) {
  48329. this.tasks = new Array();
  48330. this.waitingTasksCount = 0;
  48331. this.useDefaultLoadingScreen = true;
  48332. this._scene = scene;
  48333. }
  48334. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  48335. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  48336. this.tasks.push(task);
  48337. return task;
  48338. };
  48339. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  48340. var task = new TextFileAssetTask(taskName, url);
  48341. this.tasks.push(task);
  48342. return task;
  48343. };
  48344. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  48345. var task = new BinaryFileAssetTask(taskName, url);
  48346. this.tasks.push(task);
  48347. return task;
  48348. };
  48349. AssetsManager.prototype.addImageTask = function (taskName, url) {
  48350. var task = new ImageAssetTask(taskName, url);
  48351. this.tasks.push(task);
  48352. return task;
  48353. };
  48354. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  48355. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48356. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  48357. this.tasks.push(task);
  48358. return task;
  48359. };
  48360. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  48361. this.waitingTasksCount--;
  48362. if (this.waitingTasksCount === 0) {
  48363. if (this.onFinish) {
  48364. this.onFinish(this.tasks);
  48365. }
  48366. this._scene.getEngine().hideLoadingUI();
  48367. }
  48368. };
  48369. AssetsManager.prototype._runTask = function (task) {
  48370. var _this = this;
  48371. task.run(this._scene, function () {
  48372. if (_this.onTaskSuccess) {
  48373. _this.onTaskSuccess(task);
  48374. }
  48375. _this._decreaseWaitingTasksCount();
  48376. }, function () {
  48377. if (_this.onTaskError) {
  48378. _this.onTaskError(task);
  48379. }
  48380. _this._decreaseWaitingTasksCount();
  48381. });
  48382. };
  48383. AssetsManager.prototype.reset = function () {
  48384. this.tasks = new Array();
  48385. return this;
  48386. };
  48387. AssetsManager.prototype.load = function () {
  48388. this.waitingTasksCount = this.tasks.length;
  48389. if (this.waitingTasksCount === 0) {
  48390. if (this.onFinish) {
  48391. this.onFinish(this.tasks);
  48392. }
  48393. return this;
  48394. }
  48395. if (this.useDefaultLoadingScreen) {
  48396. this._scene.getEngine().displayLoadingUI();
  48397. }
  48398. for (var index = 0; index < this.tasks.length; index++) {
  48399. var task = this.tasks[index];
  48400. this._runTask(task);
  48401. }
  48402. return this;
  48403. };
  48404. return AssetsManager;
  48405. }());
  48406. BABYLON.AssetsManager = AssetsManager;
  48407. })(BABYLON || (BABYLON = {}));
  48408. //# sourceMappingURL=babylon.assetsManager.js.map
  48409. var BABYLON;
  48410. (function (BABYLON) {
  48411. var VRCameraMetrics = (function () {
  48412. function VRCameraMetrics() {
  48413. this.compensateDistortion = true;
  48414. }
  48415. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  48416. get: function () {
  48417. return this.hResolution / (2 * this.vResolution);
  48418. },
  48419. enumerable: true,
  48420. configurable: true
  48421. });
  48422. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  48423. get: function () {
  48424. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  48425. },
  48426. enumerable: true,
  48427. configurable: true
  48428. });
  48429. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  48430. get: function () {
  48431. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  48432. var h = (4 * meters) / this.hScreenSize;
  48433. return BABYLON.Matrix.Translation(h, 0, 0);
  48434. },
  48435. enumerable: true,
  48436. configurable: true
  48437. });
  48438. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  48439. get: function () {
  48440. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  48441. var h = (4 * meters) / this.hScreenSize;
  48442. return BABYLON.Matrix.Translation(-h, 0, 0);
  48443. },
  48444. enumerable: true,
  48445. configurable: true
  48446. });
  48447. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  48448. get: function () {
  48449. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  48450. },
  48451. enumerable: true,
  48452. configurable: true
  48453. });
  48454. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  48455. get: function () {
  48456. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  48457. },
  48458. enumerable: true,
  48459. configurable: true
  48460. });
  48461. VRCameraMetrics.GetDefault = function () {
  48462. var result = new VRCameraMetrics();
  48463. result.hResolution = 1280;
  48464. result.vResolution = 800;
  48465. result.hScreenSize = 0.149759993;
  48466. result.vScreenSize = 0.0935999975;
  48467. result.vScreenCenter = 0.0467999987;
  48468. result.eyeToScreenDistance = 0.0410000011;
  48469. result.lensSeparationDistance = 0.0635000020;
  48470. result.interpupillaryDistance = 0.0640000030;
  48471. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  48472. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  48473. result.postProcessScaleFactor = 1.714605507808412;
  48474. result.lensCenterOffset = 0.151976421;
  48475. return result;
  48476. };
  48477. return VRCameraMetrics;
  48478. }());
  48479. BABYLON.VRCameraMetrics = VRCameraMetrics;
  48480. })(BABYLON || (BABYLON = {}));
  48481. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  48482. var BABYLON;
  48483. (function (BABYLON) {
  48484. var WebVRFreeCamera = (function (_super) {
  48485. __extends(WebVRFreeCamera, _super);
  48486. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  48487. if (compensateDistortion === void 0) { compensateDistortion = false; }
  48488. if (webVROptions === void 0) { webVROptions = {}; }
  48489. var _this = _super.call(this, name, position, scene) || this;
  48490. _this.webVROptions = webVROptions;
  48491. _this._vrDevice = null;
  48492. _this.rawPose = null;
  48493. _this._vrEnabled = false;
  48494. _this._attached = false;
  48495. _this._positionOffset = BABYLON.Vector3.Zero();
  48496. _this.devicePosition = BABYLON.Vector3.Zero();
  48497. _this.deviceScaleFactor = 1;
  48498. _this.controllers = [];
  48499. _this.rotationQuaternion = new BABYLON.Quaternion();
  48500. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  48501. if (_this.webVROptions && _this.webVROptions.positionScale) {
  48502. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  48503. }
  48504. //enable VR
  48505. _this.getEngine().initWebVR();
  48506. if (!_this.getEngine().vrDisplaysPromise) {
  48507. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  48508. }
  48509. else {
  48510. _this._frameData = new VRFrameData();
  48511. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  48512. if (devices.length > 0) {
  48513. _this._vrEnabled = true;
  48514. if (_this.webVROptions.displayName) {
  48515. var found = devices.some(function (device) {
  48516. if (device.displayName === _this.webVROptions.displayName) {
  48517. _this._vrDevice = device;
  48518. return true;
  48519. }
  48520. else {
  48521. return false;
  48522. }
  48523. });
  48524. if (!found) {
  48525. _this._vrDevice = devices[0];
  48526. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  48527. }
  48528. }
  48529. else {
  48530. //choose the first one
  48531. _this._vrDevice = devices[0];
  48532. }
  48533. //reset the rig parameters.
  48534. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  48535. if (_this._attached) {
  48536. _this.getEngine().enableVR(_this._vrDevice);
  48537. }
  48538. }
  48539. else {
  48540. BABYLON.Tools.Error("No WebVR devices found!");
  48541. }
  48542. });
  48543. }
  48544. // try to attach the controllers, if found.
  48545. _this.initControllers();
  48546. return _this;
  48547. }
  48548. WebVRFreeCamera.prototype._checkInputs = function () {
  48549. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  48550. var currentPose = this._frameData.pose;
  48551. this.updateFromDevice(currentPose);
  48552. }
  48553. _super.prototype._checkInputs.call(this);
  48554. };
  48555. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  48556. if (poseData && poseData.orientation) {
  48557. this.rawPose = poseData;
  48558. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  48559. if (this.getScene().useRightHandedSystem) {
  48560. this.deviceRotationQuaternion.z *= -1;
  48561. this.deviceRotationQuaternion.w *= -1;
  48562. }
  48563. if (this.webVROptions.trackPosition && this.rawPose.position) {
  48564. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  48565. if (this.getScene().useRightHandedSystem) {
  48566. this.devicePosition.z *= -1;
  48567. }
  48568. }
  48569. }
  48570. };
  48571. /**
  48572. * WebVR's attach control will start broadcasting frames to the device.
  48573. * Note that in certain browsers (chrome for example) this function must be called
  48574. * within a user-interaction callback. Example:
  48575. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  48576. *
  48577. * @param {HTMLElement} element
  48578. * @param {boolean} [noPreventDefault]
  48579. *
  48580. * @memberOf WebVRFreeCamera
  48581. */
  48582. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48583. _super.prototype.attachControl.call(this, element, noPreventDefault);
  48584. this._attached = true;
  48585. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  48586. if (this._vrEnabled) {
  48587. this.getEngine().enableVR(this._vrDevice);
  48588. }
  48589. };
  48590. WebVRFreeCamera.prototype.detachControl = function (element) {
  48591. _super.prototype.detachControl.call(this, element);
  48592. this._vrEnabled = false;
  48593. this._attached = false;
  48594. this.getEngine().disableVR();
  48595. };
  48596. WebVRFreeCamera.prototype.getClassName = function () {
  48597. return "WebVRFreeCamera";
  48598. };
  48599. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  48600. //uses the vrDisplay's "resetPose()".
  48601. //pitch and roll won't be affected.
  48602. this._vrDevice.resetPose();
  48603. };
  48604. /**
  48605. * This function is called by the two RIG cameras.
  48606. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  48607. */
  48608. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  48609. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  48610. if (!this.getScene().useRightHandedSystem) {
  48611. [2, 6, 8, 9, 14].forEach(function (num) {
  48612. viewArray[num] *= -1;
  48613. });
  48614. }
  48615. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  48616. var parentCamera = this._cameraRigParams["parentCamera"];
  48617. // should the view matrix be updated with scale and position offset?
  48618. if (parentCamera.position.lengthSquared() || parentCamera.deviceScaleFactor !== 1) {
  48619. this._webvrViewMatrix.invert();
  48620. // scale the position, if set
  48621. if (parentCamera.deviceScaleFactor) {
  48622. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  48623. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  48624. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  48625. }
  48626. // change the position (for "teleporting");
  48627. this._webvrViewMatrix.m[12] += parentCamera.position.x;
  48628. this._webvrViewMatrix.m[13] += parentCamera.position.y;
  48629. this._webvrViewMatrix.m[14] += parentCamera.position.z;
  48630. this._webvrViewMatrix.invert();
  48631. }
  48632. // is rotation offset set?
  48633. if (!BABYLON.Quaternion.IsIdentity(this.rotationQuaternion)) {
  48634. this.rotationQuaternion.toRotationMatrix(this._tempMatrix);
  48635. this._tempMatrix.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  48636. }
  48637. this._updateCameraRotationMatrix();
  48638. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48639. // Computing target for getTarget()
  48640. this._webvrViewMatrix.getTranslationToRef(this._positionOffset);
  48641. this._positionOffset.addToRef(this._transformedReferencePoint, this._currentTarget);
  48642. return this._webvrViewMatrix;
  48643. };
  48644. WebVRFreeCamera.prototype._updateCameraRotationMatrix = function () {
  48645. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  48646. };
  48647. WebVRFreeCamera.prototype._isSynchronizedViewMatrix = function () {
  48648. return false;
  48649. };
  48650. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  48651. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  48652. //babylon compatible matrix
  48653. if (!this.getScene().useRightHandedSystem) {
  48654. [8, 9, 10, 11].forEach(function (num) {
  48655. projectionArray[num] *= -1;
  48656. });
  48657. }
  48658. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  48659. return this._projectionMatrix;
  48660. };
  48661. WebVRFreeCamera.prototype.initControllers = function () {
  48662. var _this = this;
  48663. this.controllers = [];
  48664. new BABYLON.Gamepads(function (gp) {
  48665. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  48666. var webVrController = gp;
  48667. webVrController.attachToPoseControlledCamera(_this);
  48668. // since this is async - sanity check. Is the controller already stored?
  48669. if (_this.controllers.indexOf(webVrController) === -1) {
  48670. //add to the controllers array
  48671. _this.controllers.push(webVrController);
  48672. //did we find enough controllers? Great! let the developer know.
  48673. if (_this.onControllersAttached && _this.controllers.length === 2) {
  48674. _this.onControllersAttached(_this.controllers);
  48675. }
  48676. }
  48677. }
  48678. });
  48679. };
  48680. return WebVRFreeCamera;
  48681. }(BABYLON.FreeCamera));
  48682. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  48683. })(BABYLON || (BABYLON = {}));
  48684. //# sourceMappingURL=babylon.webVRCamera.js.map
  48685. var BABYLON;
  48686. (function (BABYLON) {
  48687. // Standard optimizations
  48688. var SceneOptimization = (function () {
  48689. function SceneOptimization(priority) {
  48690. if (priority === void 0) { priority = 0; }
  48691. this.priority = priority;
  48692. this.apply = function (scene) {
  48693. return true; // Return true if everything that can be done was applied
  48694. };
  48695. }
  48696. return SceneOptimization;
  48697. }());
  48698. BABYLON.SceneOptimization = SceneOptimization;
  48699. var TextureOptimization = (function (_super) {
  48700. __extends(TextureOptimization, _super);
  48701. function TextureOptimization(priority, maximumSize) {
  48702. if (priority === void 0) { priority = 0; }
  48703. if (maximumSize === void 0) { maximumSize = 1024; }
  48704. var _this = _super.call(this, priority) || this;
  48705. _this.priority = priority;
  48706. _this.maximumSize = maximumSize;
  48707. _this.apply = function (scene) {
  48708. var allDone = true;
  48709. for (var index = 0; index < scene.textures.length; index++) {
  48710. var texture = scene.textures[index];
  48711. if (!texture.canRescale) {
  48712. continue;
  48713. }
  48714. var currentSize = texture.getSize();
  48715. var maxDimension = Math.max(currentSize.width, currentSize.height);
  48716. if (maxDimension > _this.maximumSize) {
  48717. texture.scale(0.5);
  48718. allDone = false;
  48719. }
  48720. }
  48721. return allDone;
  48722. };
  48723. return _this;
  48724. }
  48725. return TextureOptimization;
  48726. }(SceneOptimization));
  48727. BABYLON.TextureOptimization = TextureOptimization;
  48728. var HardwareScalingOptimization = (function (_super) {
  48729. __extends(HardwareScalingOptimization, _super);
  48730. function HardwareScalingOptimization(priority, maximumScale) {
  48731. if (priority === void 0) { priority = 0; }
  48732. if (maximumScale === void 0) { maximumScale = 2; }
  48733. var _this = _super.call(this, priority) || this;
  48734. _this.priority = priority;
  48735. _this.maximumScale = maximumScale;
  48736. _this._currentScale = 1;
  48737. _this.apply = function (scene) {
  48738. _this._currentScale++;
  48739. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  48740. return _this._currentScale >= _this.maximumScale;
  48741. };
  48742. return _this;
  48743. }
  48744. return HardwareScalingOptimization;
  48745. }(SceneOptimization));
  48746. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  48747. var ShadowsOptimization = (function (_super) {
  48748. __extends(ShadowsOptimization, _super);
  48749. function ShadowsOptimization() {
  48750. var _this = _super.apply(this, arguments) || this;
  48751. _this.apply = function (scene) {
  48752. scene.shadowsEnabled = false;
  48753. return true;
  48754. };
  48755. return _this;
  48756. }
  48757. return ShadowsOptimization;
  48758. }(SceneOptimization));
  48759. BABYLON.ShadowsOptimization = ShadowsOptimization;
  48760. var PostProcessesOptimization = (function (_super) {
  48761. __extends(PostProcessesOptimization, _super);
  48762. function PostProcessesOptimization() {
  48763. var _this = _super.apply(this, arguments) || this;
  48764. _this.apply = function (scene) {
  48765. scene.postProcessesEnabled = false;
  48766. return true;
  48767. };
  48768. return _this;
  48769. }
  48770. return PostProcessesOptimization;
  48771. }(SceneOptimization));
  48772. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  48773. var LensFlaresOptimization = (function (_super) {
  48774. __extends(LensFlaresOptimization, _super);
  48775. function LensFlaresOptimization() {
  48776. var _this = _super.apply(this, arguments) || this;
  48777. _this.apply = function (scene) {
  48778. scene.lensFlaresEnabled = false;
  48779. return true;
  48780. };
  48781. return _this;
  48782. }
  48783. return LensFlaresOptimization;
  48784. }(SceneOptimization));
  48785. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  48786. var ParticlesOptimization = (function (_super) {
  48787. __extends(ParticlesOptimization, _super);
  48788. function ParticlesOptimization() {
  48789. var _this = _super.apply(this, arguments) || this;
  48790. _this.apply = function (scene) {
  48791. scene.particlesEnabled = false;
  48792. return true;
  48793. };
  48794. return _this;
  48795. }
  48796. return ParticlesOptimization;
  48797. }(SceneOptimization));
  48798. BABYLON.ParticlesOptimization = ParticlesOptimization;
  48799. var RenderTargetsOptimization = (function (_super) {
  48800. __extends(RenderTargetsOptimization, _super);
  48801. function RenderTargetsOptimization() {
  48802. var _this = _super.apply(this, arguments) || this;
  48803. _this.apply = function (scene) {
  48804. scene.renderTargetsEnabled = false;
  48805. return true;
  48806. };
  48807. return _this;
  48808. }
  48809. return RenderTargetsOptimization;
  48810. }(SceneOptimization));
  48811. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  48812. var MergeMeshesOptimization = (function (_super) {
  48813. __extends(MergeMeshesOptimization, _super);
  48814. function MergeMeshesOptimization() {
  48815. var _this = _super.apply(this, arguments) || this;
  48816. _this._canBeMerged = function (abstractMesh) {
  48817. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  48818. return false;
  48819. }
  48820. var mesh = abstractMesh;
  48821. if (!mesh.isVisible || !mesh.isEnabled()) {
  48822. return false;
  48823. }
  48824. if (mesh.instances.length > 0) {
  48825. return false;
  48826. }
  48827. if (mesh.skeleton || mesh.hasLODLevels) {
  48828. return false;
  48829. }
  48830. if (mesh.parent) {
  48831. return false;
  48832. }
  48833. return true;
  48834. };
  48835. _this.apply = function (scene, updateSelectionTree) {
  48836. var globalPool = scene.meshes.slice(0);
  48837. var globalLength = globalPool.length;
  48838. for (var index = 0; index < globalLength; index++) {
  48839. var currentPool = new Array();
  48840. var current = globalPool[index];
  48841. // Checks
  48842. if (!_this._canBeMerged(current)) {
  48843. continue;
  48844. }
  48845. currentPool.push(current);
  48846. // Find compatible meshes
  48847. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  48848. var otherMesh = globalPool[subIndex];
  48849. if (!_this._canBeMerged(otherMesh)) {
  48850. continue;
  48851. }
  48852. if (otherMesh.material !== current.material) {
  48853. continue;
  48854. }
  48855. if (otherMesh.checkCollisions !== current.checkCollisions) {
  48856. continue;
  48857. }
  48858. currentPool.push(otherMesh);
  48859. globalLength--;
  48860. globalPool.splice(subIndex, 1);
  48861. subIndex--;
  48862. }
  48863. if (currentPool.length < 2) {
  48864. continue;
  48865. }
  48866. // Merge meshes
  48867. BABYLON.Mesh.MergeMeshes(currentPool);
  48868. }
  48869. if (updateSelectionTree != undefined) {
  48870. if (updateSelectionTree) {
  48871. scene.createOrUpdateSelectionOctree();
  48872. }
  48873. }
  48874. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  48875. scene.createOrUpdateSelectionOctree();
  48876. }
  48877. return true;
  48878. };
  48879. return _this;
  48880. }
  48881. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  48882. get: function () {
  48883. return MergeMeshesOptimization._UpdateSelectionTree;
  48884. },
  48885. set: function (value) {
  48886. MergeMeshesOptimization._UpdateSelectionTree = value;
  48887. },
  48888. enumerable: true,
  48889. configurable: true
  48890. });
  48891. return MergeMeshesOptimization;
  48892. }(SceneOptimization));
  48893. MergeMeshesOptimization._UpdateSelectionTree = false;
  48894. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  48895. // Options
  48896. var SceneOptimizerOptions = (function () {
  48897. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  48898. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  48899. if (trackerDuration === void 0) { trackerDuration = 2000; }
  48900. this.targetFrameRate = targetFrameRate;
  48901. this.trackerDuration = trackerDuration;
  48902. this.optimizations = new Array();
  48903. }
  48904. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  48905. var result = new SceneOptimizerOptions(targetFrameRate);
  48906. var priority = 0;
  48907. result.optimizations.push(new MergeMeshesOptimization(priority));
  48908. result.optimizations.push(new ShadowsOptimization(priority));
  48909. result.optimizations.push(new LensFlaresOptimization(priority));
  48910. // Next priority
  48911. priority++;
  48912. result.optimizations.push(new PostProcessesOptimization(priority));
  48913. result.optimizations.push(new ParticlesOptimization(priority));
  48914. // Next priority
  48915. priority++;
  48916. result.optimizations.push(new TextureOptimization(priority, 1024));
  48917. return result;
  48918. };
  48919. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  48920. var result = new SceneOptimizerOptions(targetFrameRate);
  48921. var priority = 0;
  48922. result.optimizations.push(new MergeMeshesOptimization(priority));
  48923. result.optimizations.push(new ShadowsOptimization(priority));
  48924. result.optimizations.push(new LensFlaresOptimization(priority));
  48925. // Next priority
  48926. priority++;
  48927. result.optimizations.push(new PostProcessesOptimization(priority));
  48928. result.optimizations.push(new ParticlesOptimization(priority));
  48929. // Next priority
  48930. priority++;
  48931. result.optimizations.push(new TextureOptimization(priority, 512));
  48932. // Next priority
  48933. priority++;
  48934. result.optimizations.push(new RenderTargetsOptimization(priority));
  48935. // Next priority
  48936. priority++;
  48937. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  48938. return result;
  48939. };
  48940. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  48941. var result = new SceneOptimizerOptions(targetFrameRate);
  48942. var priority = 0;
  48943. result.optimizations.push(new MergeMeshesOptimization(priority));
  48944. result.optimizations.push(new ShadowsOptimization(priority));
  48945. result.optimizations.push(new LensFlaresOptimization(priority));
  48946. // Next priority
  48947. priority++;
  48948. result.optimizations.push(new PostProcessesOptimization(priority));
  48949. result.optimizations.push(new ParticlesOptimization(priority));
  48950. // Next priority
  48951. priority++;
  48952. result.optimizations.push(new TextureOptimization(priority, 256));
  48953. // Next priority
  48954. priority++;
  48955. result.optimizations.push(new RenderTargetsOptimization(priority));
  48956. // Next priority
  48957. priority++;
  48958. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  48959. return result;
  48960. };
  48961. return SceneOptimizerOptions;
  48962. }());
  48963. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  48964. // Scene optimizer tool
  48965. var SceneOptimizer = (function () {
  48966. function SceneOptimizer() {
  48967. }
  48968. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  48969. // TODO: add an epsilon
  48970. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  48971. if (onSuccess) {
  48972. onSuccess();
  48973. }
  48974. return;
  48975. }
  48976. // Apply current level of optimizations
  48977. var allDone = true;
  48978. var noOptimizationApplied = true;
  48979. for (var index = 0; index < options.optimizations.length; index++) {
  48980. var optimization = options.optimizations[index];
  48981. if (optimization.priority === currentPriorityLevel) {
  48982. noOptimizationApplied = false;
  48983. allDone = allDone && optimization.apply(scene);
  48984. }
  48985. }
  48986. // If no optimization was applied, this is a failure :(
  48987. if (noOptimizationApplied) {
  48988. if (onFailure) {
  48989. onFailure();
  48990. }
  48991. return;
  48992. }
  48993. // If all optimizations were done, move to next level
  48994. if (allDone) {
  48995. currentPriorityLevel++;
  48996. }
  48997. // Let's the system running for a specific amount of time before checking FPS
  48998. scene.executeWhenReady(function () {
  48999. setTimeout(function () {
  49000. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49001. }, options.trackerDuration);
  49002. });
  49003. };
  49004. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49005. if (!options) {
  49006. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49007. }
  49008. // Let's the system running for a specific amount of time before checking FPS
  49009. scene.executeWhenReady(function () {
  49010. setTimeout(function () {
  49011. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49012. }, options.trackerDuration);
  49013. });
  49014. };
  49015. return SceneOptimizer;
  49016. }());
  49017. BABYLON.SceneOptimizer = SceneOptimizer;
  49018. })(BABYLON || (BABYLON = {}));
  49019. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  49020. var BABYLON;
  49021. (function (BABYLON) {
  49022. var Internals;
  49023. (function (Internals) {
  49024. var MeshLODLevel = (function () {
  49025. function MeshLODLevel(distance, mesh) {
  49026. this.distance = distance;
  49027. this.mesh = mesh;
  49028. }
  49029. return MeshLODLevel;
  49030. }());
  49031. Internals.MeshLODLevel = MeshLODLevel;
  49032. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49033. })(BABYLON || (BABYLON = {}));
  49034. //# sourceMappingURL=babylon.meshLODLevel.js.map
  49035. var BABYLON;
  49036. (function (BABYLON) {
  49037. var RawTexture = (function (_super) {
  49038. __extends(RawTexture, _super);
  49039. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49040. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49041. if (invertY === void 0) { invertY = false; }
  49042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49043. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49044. _this.format = format;
  49045. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49046. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49047. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49048. return _this;
  49049. }
  49050. RawTexture.prototype.update = function (data) {
  49051. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49052. };
  49053. // Statics
  49054. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49055. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49056. if (invertY === void 0) { invertY = false; }
  49057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49058. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49059. };
  49060. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49061. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49062. if (invertY === void 0) { invertY = false; }
  49063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49064. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49065. };
  49066. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49067. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49068. if (invertY === void 0) { invertY = false; }
  49069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49070. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49071. };
  49072. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49073. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49074. if (invertY === void 0) { invertY = false; }
  49075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49076. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49077. };
  49078. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49079. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49080. if (invertY === void 0) { invertY = false; }
  49081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49082. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49083. };
  49084. return RawTexture;
  49085. }(BABYLON.Texture));
  49086. BABYLON.RawTexture = RawTexture;
  49087. })(BABYLON || (BABYLON = {}));
  49088. //# sourceMappingURL=babylon.rawTexture.js.map
  49089. /// <reference path="..\Math\babylon.math.ts" />
  49090. var BABYLON;
  49091. (function (BABYLON) {
  49092. var IndexedVector2 = (function (_super) {
  49093. __extends(IndexedVector2, _super);
  49094. function IndexedVector2(original, index) {
  49095. var _this = _super.call(this, original.x, original.y) || this;
  49096. _this.index = index;
  49097. return _this;
  49098. }
  49099. return IndexedVector2;
  49100. }(BABYLON.Vector2));
  49101. var PolygonPoints = (function () {
  49102. function PolygonPoints() {
  49103. this.elements = new Array();
  49104. }
  49105. PolygonPoints.prototype.add = function (originalPoints) {
  49106. var _this = this;
  49107. var result = new Array();
  49108. originalPoints.forEach(function (point) {
  49109. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49110. var newPoint = new IndexedVector2(point, _this.elements.length);
  49111. result.push(newPoint);
  49112. _this.elements.push(newPoint);
  49113. }
  49114. });
  49115. return result;
  49116. };
  49117. PolygonPoints.prototype.computeBounds = function () {
  49118. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49119. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49120. this.elements.forEach(function (point) {
  49121. // x
  49122. if (point.x < lmin.x) {
  49123. lmin.x = point.x;
  49124. }
  49125. else if (point.x > lmax.x) {
  49126. lmax.x = point.x;
  49127. }
  49128. // y
  49129. if (point.y < lmin.y) {
  49130. lmin.y = point.y;
  49131. }
  49132. else if (point.y > lmax.y) {
  49133. lmax.y = point.y;
  49134. }
  49135. });
  49136. return {
  49137. min: lmin,
  49138. max: lmax,
  49139. width: lmax.x - lmin.x,
  49140. height: lmax.y - lmin.y
  49141. };
  49142. };
  49143. return PolygonPoints;
  49144. }());
  49145. var Polygon = (function () {
  49146. function Polygon() {
  49147. }
  49148. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  49149. return [
  49150. new BABYLON.Vector2(xmin, ymin),
  49151. new BABYLON.Vector2(xmax, ymin),
  49152. new BABYLON.Vector2(xmax, ymax),
  49153. new BABYLON.Vector2(xmin, ymax)
  49154. ];
  49155. };
  49156. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  49157. if (cx === void 0) { cx = 0; }
  49158. if (cy === void 0) { cy = 0; }
  49159. if (numberOfSides === void 0) { numberOfSides = 32; }
  49160. var result = new Array();
  49161. var angle = 0;
  49162. var increment = (Math.PI * 2) / numberOfSides;
  49163. for (var i = 0; i < numberOfSides; i++) {
  49164. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  49165. angle -= increment;
  49166. }
  49167. return result;
  49168. };
  49169. Polygon.Parse = function (input) {
  49170. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  49171. var i, result = [];
  49172. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  49173. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  49174. }
  49175. return result;
  49176. };
  49177. Polygon.StartingAt = function (x, y) {
  49178. return BABYLON.Path2.StartingAt(x, y);
  49179. };
  49180. return Polygon;
  49181. }());
  49182. BABYLON.Polygon = Polygon;
  49183. var PolygonMeshBuilder = (function () {
  49184. function PolygonMeshBuilder(name, contours, scene) {
  49185. this._points = new PolygonPoints();
  49186. this._outlinepoints = new PolygonPoints();
  49187. this._holes = [];
  49188. this._epoints = new Array();
  49189. this._eholes = new Array();
  49190. this._name = name;
  49191. this._scene = scene;
  49192. var points;
  49193. if (contours instanceof BABYLON.Path2) {
  49194. points = contours.getPoints();
  49195. }
  49196. else {
  49197. points = contours;
  49198. }
  49199. this._addToepoint(points);
  49200. this._points.add(points);
  49201. this._outlinepoints.add(points);
  49202. }
  49203. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  49204. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  49205. var p = points_1[_i];
  49206. this._epoints.push(p.x, p.y);
  49207. }
  49208. };
  49209. PolygonMeshBuilder.prototype.addHole = function (hole) {
  49210. this._points.add(hole);
  49211. var holepoints = new PolygonPoints();
  49212. holepoints.add(hole);
  49213. this._holes.push(holepoints);
  49214. this._eholes.push(this._epoints.length / 2);
  49215. this._addToepoint(hole);
  49216. return this;
  49217. };
  49218. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  49219. var _this = this;
  49220. if (updatable === void 0) { updatable = false; }
  49221. var result = new BABYLON.Mesh(this._name, this._scene);
  49222. var normals = [];
  49223. var positions = [];
  49224. var uvs = [];
  49225. var bounds = this._points.computeBounds();
  49226. this._points.elements.forEach(function (p) {
  49227. normals.push(0, 1.0, 0);
  49228. positions.push(p.x, 0, p.y);
  49229. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  49230. });
  49231. var indices = [];
  49232. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  49233. for (var i = 0; i < res.length; i++) {
  49234. indices.push(res[i]);
  49235. }
  49236. if (depth > 0) {
  49237. var positionscount = (positions.length / 3); //get the current pointcount
  49238. this._points.elements.forEach(function (p) {
  49239. normals.push(0, -1.0, 0);
  49240. positions.push(p.x, -depth, p.y);
  49241. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  49242. });
  49243. var totalCount = indices.length;
  49244. for (var i = 0; i < totalCount; i += 3) {
  49245. var i0 = indices[i + 0];
  49246. var i1 = indices[i + 1];
  49247. var i2 = indices[i + 2];
  49248. indices.push(i2 + positionscount);
  49249. indices.push(i1 + positionscount);
  49250. indices.push(i0 + positionscount);
  49251. }
  49252. //Add the sides
  49253. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  49254. this._holes.forEach(function (hole) {
  49255. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  49256. });
  49257. }
  49258. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  49259. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  49260. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  49261. result.setIndices(indices);
  49262. return result;
  49263. };
  49264. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  49265. var StartIndex = positions.length / 3;
  49266. var ulength = 0;
  49267. for (var i = 0; i < points.elements.length; i++) {
  49268. var p = points.elements[i];
  49269. var p1;
  49270. if ((i + 1) > points.elements.length - 1) {
  49271. p1 = points.elements[0];
  49272. }
  49273. else {
  49274. p1 = points.elements[i + 1];
  49275. }
  49276. positions.push(p.x, 0, p.y);
  49277. positions.push(p.x, -depth, p.y);
  49278. positions.push(p1.x, 0, p1.y);
  49279. positions.push(p1.x, -depth, p1.y);
  49280. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  49281. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  49282. var v3 = v2.subtract(v1);
  49283. var v4 = new BABYLON.Vector3(0, 1, 0);
  49284. var vn = BABYLON.Vector3.Cross(v3, v4);
  49285. vn = vn.normalize();
  49286. uvs.push(ulength / bounds.width, 0);
  49287. uvs.push(ulength / bounds.width, 1);
  49288. ulength += v3.length();
  49289. uvs.push((ulength / bounds.width), 0);
  49290. uvs.push((ulength / bounds.width), 1);
  49291. if (!flip) {
  49292. normals.push(-vn.x, -vn.y, -vn.z);
  49293. normals.push(-vn.x, -vn.y, -vn.z);
  49294. normals.push(-vn.x, -vn.y, -vn.z);
  49295. normals.push(-vn.x, -vn.y, -vn.z);
  49296. indices.push(StartIndex);
  49297. indices.push(StartIndex + 1);
  49298. indices.push(StartIndex + 2);
  49299. indices.push(StartIndex + 1);
  49300. indices.push(StartIndex + 3);
  49301. indices.push(StartIndex + 2);
  49302. }
  49303. else {
  49304. normals.push(vn.x, vn.y, vn.z);
  49305. normals.push(vn.x, vn.y, vn.z);
  49306. normals.push(vn.x, vn.y, vn.z);
  49307. normals.push(vn.x, vn.y, vn.z);
  49308. indices.push(StartIndex);
  49309. indices.push(StartIndex + 2);
  49310. indices.push(StartIndex + 1);
  49311. indices.push(StartIndex + 1);
  49312. indices.push(StartIndex + 2);
  49313. indices.push(StartIndex + 3);
  49314. }
  49315. StartIndex += 4;
  49316. }
  49317. ;
  49318. };
  49319. return PolygonMeshBuilder;
  49320. }());
  49321. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  49322. })(BABYLON || (BABYLON = {}));
  49323. //# sourceMappingURL=babylon.polygonMesh.js.map
  49324. var BABYLON;
  49325. (function (BABYLON) {
  49326. var Octree = (function () {
  49327. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  49328. if (maxDepth === void 0) { maxDepth = 2; }
  49329. this.maxDepth = maxDepth;
  49330. this.dynamicContent = new Array();
  49331. this._maxBlockCapacity = maxBlockCapacity || 64;
  49332. this._selectionContent = new BABYLON.SmartArray(1024);
  49333. this._creationFunc = creationFunc;
  49334. }
  49335. // Methods
  49336. Octree.prototype.update = function (worldMin, worldMax, entries) {
  49337. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  49338. };
  49339. Octree.prototype.addMesh = function (entry) {
  49340. for (var index = 0; index < this.blocks.length; index++) {
  49341. var block = this.blocks[index];
  49342. block.addEntry(entry);
  49343. }
  49344. };
  49345. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  49346. this._selectionContent.reset();
  49347. for (var index = 0; index < this.blocks.length; index++) {
  49348. var block = this.blocks[index];
  49349. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  49350. }
  49351. if (allowDuplicate) {
  49352. this._selectionContent.concat(this.dynamicContent);
  49353. }
  49354. else {
  49355. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  49356. }
  49357. return this._selectionContent;
  49358. };
  49359. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  49360. this._selectionContent.reset();
  49361. for (var index = 0; index < this.blocks.length; index++) {
  49362. var block = this.blocks[index];
  49363. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  49364. }
  49365. if (allowDuplicate) {
  49366. this._selectionContent.concat(this.dynamicContent);
  49367. }
  49368. else {
  49369. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  49370. }
  49371. return this._selectionContent;
  49372. };
  49373. Octree.prototype.intersectsRay = function (ray) {
  49374. this._selectionContent.reset();
  49375. for (var index = 0; index < this.blocks.length; index++) {
  49376. var block = this.blocks[index];
  49377. block.intersectsRay(ray, this._selectionContent);
  49378. }
  49379. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  49380. return this._selectionContent;
  49381. };
  49382. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  49383. target.blocks = new Array();
  49384. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  49385. // Segmenting space
  49386. for (var x = 0; x < 2; x++) {
  49387. for (var y = 0; y < 2; y++) {
  49388. for (var z = 0; z < 2; z++) {
  49389. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  49390. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  49391. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  49392. block.addEntries(entries);
  49393. target.blocks.push(block);
  49394. }
  49395. }
  49396. }
  49397. };
  49398. return Octree;
  49399. }());
  49400. Octree.CreationFuncForMeshes = function (entry, block) {
  49401. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  49402. block.entries.push(entry);
  49403. }
  49404. };
  49405. Octree.CreationFuncForSubMeshes = function (entry, block) {
  49406. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  49407. block.entries.push(entry);
  49408. }
  49409. };
  49410. BABYLON.Octree = Octree;
  49411. })(BABYLON || (BABYLON = {}));
  49412. //# sourceMappingURL=babylon.octree.js.map
  49413. var BABYLON;
  49414. (function (BABYLON) {
  49415. var OctreeBlock = (function () {
  49416. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  49417. this.entries = new Array();
  49418. this._boundingVectors = new Array();
  49419. this._capacity = capacity;
  49420. this._depth = depth;
  49421. this._maxDepth = maxDepth;
  49422. this._creationFunc = creationFunc;
  49423. this._minPoint = minPoint;
  49424. this._maxPoint = maxPoint;
  49425. this._boundingVectors.push(minPoint.clone());
  49426. this._boundingVectors.push(maxPoint.clone());
  49427. this._boundingVectors.push(minPoint.clone());
  49428. this._boundingVectors[2].x = maxPoint.x;
  49429. this._boundingVectors.push(minPoint.clone());
  49430. this._boundingVectors[3].y = maxPoint.y;
  49431. this._boundingVectors.push(minPoint.clone());
  49432. this._boundingVectors[4].z = maxPoint.z;
  49433. this._boundingVectors.push(maxPoint.clone());
  49434. this._boundingVectors[5].z = minPoint.z;
  49435. this._boundingVectors.push(maxPoint.clone());
  49436. this._boundingVectors[6].x = minPoint.x;
  49437. this._boundingVectors.push(maxPoint.clone());
  49438. this._boundingVectors[7].y = minPoint.y;
  49439. }
  49440. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  49441. // Property
  49442. get: function () {
  49443. return this._capacity;
  49444. },
  49445. enumerable: true,
  49446. configurable: true
  49447. });
  49448. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  49449. get: function () {
  49450. return this._minPoint;
  49451. },
  49452. enumerable: true,
  49453. configurable: true
  49454. });
  49455. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  49456. get: function () {
  49457. return this._maxPoint;
  49458. },
  49459. enumerable: true,
  49460. configurable: true
  49461. });
  49462. // Methods
  49463. OctreeBlock.prototype.addEntry = function (entry) {
  49464. if (this.blocks) {
  49465. for (var index = 0; index < this.blocks.length; index++) {
  49466. var block = this.blocks[index];
  49467. block.addEntry(entry);
  49468. }
  49469. return;
  49470. }
  49471. this._creationFunc(entry, this);
  49472. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  49473. this.createInnerBlocks();
  49474. }
  49475. };
  49476. OctreeBlock.prototype.addEntries = function (entries) {
  49477. for (var index = 0; index < entries.length; index++) {
  49478. var mesh = entries[index];
  49479. this.addEntry(mesh);
  49480. }
  49481. };
  49482. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  49483. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  49484. if (this.blocks) {
  49485. for (var index = 0; index < this.blocks.length; index++) {
  49486. var block = this.blocks[index];
  49487. block.select(frustumPlanes, selection, allowDuplicate);
  49488. }
  49489. return;
  49490. }
  49491. if (allowDuplicate) {
  49492. selection.concat(this.entries);
  49493. }
  49494. else {
  49495. selection.concatWithNoDuplicate(this.entries);
  49496. }
  49497. }
  49498. };
  49499. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  49500. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  49501. if (this.blocks) {
  49502. for (var index = 0; index < this.blocks.length; index++) {
  49503. var block = this.blocks[index];
  49504. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  49505. }
  49506. return;
  49507. }
  49508. if (allowDuplicate) {
  49509. selection.concat(this.entries);
  49510. }
  49511. else {
  49512. selection.concatWithNoDuplicate(this.entries);
  49513. }
  49514. }
  49515. };
  49516. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  49517. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  49518. if (this.blocks) {
  49519. for (var index = 0; index < this.blocks.length; index++) {
  49520. var block = this.blocks[index];
  49521. block.intersectsRay(ray, selection);
  49522. }
  49523. return;
  49524. }
  49525. selection.concatWithNoDuplicate(this.entries);
  49526. }
  49527. };
  49528. OctreeBlock.prototype.createInnerBlocks = function () {
  49529. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  49530. };
  49531. return OctreeBlock;
  49532. }());
  49533. BABYLON.OctreeBlock = OctreeBlock;
  49534. })(BABYLON || (BABYLON = {}));
  49535. //# sourceMappingURL=babylon.octreeBlock.js.map
  49536. var BABYLON;
  49537. (function (BABYLON) {
  49538. var BlurPostProcess = (function (_super) {
  49539. __extends(BlurPostProcess, _super);
  49540. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  49541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49542. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  49543. _this.direction = direction;
  49544. _this.blurWidth = blurWidth;
  49545. _this.onApplyObservable.add(function (effect) {
  49546. effect.setFloat2("screenSize", _this.width, _this.height);
  49547. effect.setVector2("direction", _this.direction);
  49548. effect.setFloat("blurWidth", _this.blurWidth);
  49549. });
  49550. return _this;
  49551. }
  49552. return BlurPostProcess;
  49553. }(BABYLON.PostProcess));
  49554. BABYLON.BlurPostProcess = BlurPostProcess;
  49555. })(BABYLON || (BABYLON = {}));
  49556. //# sourceMappingURL=babylon.blurPostProcess.js.map
  49557. var BABYLON;
  49558. (function (BABYLON) {
  49559. var RefractionPostProcess = (function (_super) {
  49560. __extends(RefractionPostProcess, _super);
  49561. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  49562. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  49563. _this.color = color;
  49564. _this.depth = depth;
  49565. _this.colorLevel = colorLevel;
  49566. _this.onActivateObservable.add(function (cam) {
  49567. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  49568. });
  49569. _this.onApplyObservable.add(function (effect) {
  49570. effect.setColor3("baseColor", _this.color);
  49571. effect.setFloat("depth", _this.depth);
  49572. effect.setFloat("colorLevel", _this.colorLevel);
  49573. effect.setTexture("refractionSampler", _this._refRexture);
  49574. });
  49575. return _this;
  49576. }
  49577. // Methods
  49578. RefractionPostProcess.prototype.dispose = function (camera) {
  49579. if (this._refRexture) {
  49580. this._refRexture.dispose();
  49581. }
  49582. _super.prototype.dispose.call(this, camera);
  49583. };
  49584. return RefractionPostProcess;
  49585. }(BABYLON.PostProcess));
  49586. BABYLON.RefractionPostProcess = RefractionPostProcess;
  49587. })(BABYLON || (BABYLON = {}));
  49588. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  49589. var BABYLON;
  49590. (function (BABYLON) {
  49591. var BlackAndWhitePostProcess = (function (_super) {
  49592. __extends(BlackAndWhitePostProcess, _super);
  49593. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  49594. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  49595. }
  49596. return BlackAndWhitePostProcess;
  49597. }(BABYLON.PostProcess));
  49598. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  49599. })(BABYLON || (BABYLON = {}));
  49600. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  49601. var BABYLON;
  49602. (function (BABYLON) {
  49603. var ConvolutionPostProcess = (function (_super) {
  49604. __extends(ConvolutionPostProcess, _super);
  49605. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  49606. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  49607. _this.kernel = kernel;
  49608. _this.onApply = function (effect) {
  49609. effect.setFloat2("screenSize", _this.width, _this.height);
  49610. effect.setArray("kernel", _this.kernel);
  49611. };
  49612. return _this;
  49613. }
  49614. return ConvolutionPostProcess;
  49615. }(BABYLON.PostProcess));
  49616. // Statics
  49617. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  49618. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  49619. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  49620. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  49621. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  49622. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  49623. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  49624. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  49625. })(BABYLON || (BABYLON = {}));
  49626. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  49627. var BABYLON;
  49628. (function (BABYLON) {
  49629. var FilterPostProcess = (function (_super) {
  49630. __extends(FilterPostProcess, _super);
  49631. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  49632. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  49633. _this.kernelMatrix = kernelMatrix;
  49634. _this.onApply = function (effect) {
  49635. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  49636. };
  49637. return _this;
  49638. }
  49639. return FilterPostProcess;
  49640. }(BABYLON.PostProcess));
  49641. BABYLON.FilterPostProcess = FilterPostProcess;
  49642. })(BABYLON || (BABYLON = {}));
  49643. //# sourceMappingURL=babylon.filterPostProcess.js.map
  49644. var BABYLON;
  49645. (function (BABYLON) {
  49646. var FxaaPostProcess = (function (_super) {
  49647. __extends(FxaaPostProcess, _super);
  49648. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49649. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  49650. _this.onSizeChangedObservable.add(function () {
  49651. _this.texelWidth = 1.0 / _this.width;
  49652. _this.texelHeight = 1.0 / _this.height;
  49653. });
  49654. _this.onApplyObservable.add(function (effect) {
  49655. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  49656. });
  49657. return _this;
  49658. }
  49659. return FxaaPostProcess;
  49660. }(BABYLON.PostProcess));
  49661. BABYLON.FxaaPostProcess = FxaaPostProcess;
  49662. })(BABYLON || (BABYLON = {}));
  49663. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  49664. var BABYLON;
  49665. (function (BABYLON) {
  49666. var StereoscopicInterlacePostProcess = (function (_super) {
  49667. __extends(StereoscopicInterlacePostProcess, _super);
  49668. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  49669. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  49670. _this._passedProcess = rigCameras[0]._rigPostProcess;
  49671. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  49672. _this.onSizeChangedObservable.add(function () {
  49673. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  49674. });
  49675. _this.onApplyObservable.add(function (effect) {
  49676. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  49677. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  49678. });
  49679. return _this;
  49680. }
  49681. return StereoscopicInterlacePostProcess;
  49682. }(BABYLON.PostProcess));
  49683. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  49684. })(BABYLON || (BABYLON = {}));
  49685. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  49686. var BABYLON;
  49687. (function (BABYLON) {
  49688. var LensFlare = (function () {
  49689. function LensFlare(size, position, color, imgUrl, system) {
  49690. this.size = size;
  49691. this.position = position;
  49692. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  49693. this.dispose = function () {
  49694. if (this.texture) {
  49695. this.texture.dispose();
  49696. }
  49697. // Remove from scene
  49698. var index = this._system.lensFlares.indexOf(this);
  49699. this._system.lensFlares.splice(index, 1);
  49700. };
  49701. this.color = color || new BABYLON.Color3(1, 1, 1);
  49702. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  49703. this._system = system;
  49704. system.lensFlares.push(this);
  49705. }
  49706. return LensFlare;
  49707. }());
  49708. BABYLON.LensFlare = LensFlare;
  49709. })(BABYLON || (BABYLON = {}));
  49710. //# sourceMappingURL=babylon.lensFlare.js.map
  49711. var BABYLON;
  49712. (function (BABYLON) {
  49713. var LensFlareSystem = (function () {
  49714. function LensFlareSystem(name, emitter, scene) {
  49715. this.name = name;
  49716. this.lensFlares = new Array();
  49717. this.borderLimit = 300;
  49718. this.viewportBorder = 0;
  49719. this.layerMask = 0x0FFFFFFF;
  49720. this._vertexBuffers = {};
  49721. this._isEnabled = true;
  49722. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49723. this._emitter = emitter;
  49724. this.id = name;
  49725. scene.lensFlareSystems.push(this);
  49726. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  49727. var engine = scene.getEngine();
  49728. // VBO
  49729. var vertices = [];
  49730. vertices.push(1, 1);
  49731. vertices.push(-1, 1);
  49732. vertices.push(-1, -1);
  49733. vertices.push(1, -1);
  49734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49735. // Indices
  49736. var indices = [];
  49737. indices.push(0);
  49738. indices.push(1);
  49739. indices.push(2);
  49740. indices.push(0);
  49741. indices.push(2);
  49742. indices.push(3);
  49743. this._indexBuffer = engine.createIndexBuffer(indices);
  49744. // Effects
  49745. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  49746. }
  49747. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  49748. get: function () {
  49749. return this._isEnabled;
  49750. },
  49751. set: function (value) {
  49752. this._isEnabled = value;
  49753. },
  49754. enumerable: true,
  49755. configurable: true
  49756. });
  49757. LensFlareSystem.prototype.getScene = function () {
  49758. return this._scene;
  49759. };
  49760. LensFlareSystem.prototype.getEmitter = function () {
  49761. return this._emitter;
  49762. };
  49763. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  49764. this._emitter = newEmitter;
  49765. };
  49766. LensFlareSystem.prototype.getEmitterPosition = function () {
  49767. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  49768. };
  49769. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  49770. var position = this.getEmitterPosition();
  49771. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  49772. this._positionX = position.x;
  49773. this._positionY = position.y;
  49774. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  49775. if (this.viewportBorder > 0) {
  49776. globalViewport.x -= this.viewportBorder;
  49777. globalViewport.y -= this.viewportBorder;
  49778. globalViewport.width += this.viewportBorder * 2;
  49779. globalViewport.height += this.viewportBorder * 2;
  49780. position.x += this.viewportBorder;
  49781. position.y += this.viewportBorder;
  49782. this._positionX += this.viewportBorder;
  49783. this._positionY += this.viewportBorder;
  49784. }
  49785. if (position.z > 0) {
  49786. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  49787. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  49788. return true;
  49789. }
  49790. return true;
  49791. }
  49792. return false;
  49793. };
  49794. LensFlareSystem.prototype._isVisible = function () {
  49795. if (!this._isEnabled) {
  49796. return false;
  49797. }
  49798. var emitterPosition = this.getEmitterPosition();
  49799. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  49800. var distance = direction.length();
  49801. direction.normalize();
  49802. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  49803. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  49804. return !pickInfo.hit || pickInfo.distance > distance;
  49805. };
  49806. LensFlareSystem.prototype.render = function () {
  49807. if (!this._effect.isReady())
  49808. return false;
  49809. var engine = this._scene.getEngine();
  49810. var viewport = this._scene.activeCamera.viewport;
  49811. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  49812. // Position
  49813. if (!this.computeEffectivePosition(globalViewport)) {
  49814. return false;
  49815. }
  49816. // Visibility
  49817. if (!this._isVisible()) {
  49818. return false;
  49819. }
  49820. // Intensity
  49821. var awayX;
  49822. var awayY;
  49823. if (this._positionX < this.borderLimit + globalViewport.x) {
  49824. awayX = this.borderLimit + globalViewport.x - this._positionX;
  49825. }
  49826. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  49827. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  49828. }
  49829. else {
  49830. awayX = 0;
  49831. }
  49832. if (this._positionY < this.borderLimit + globalViewport.y) {
  49833. awayY = this.borderLimit + globalViewport.y - this._positionY;
  49834. }
  49835. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  49836. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  49837. }
  49838. else {
  49839. awayY = 0;
  49840. }
  49841. var away = (awayX > awayY) ? awayX : awayY;
  49842. away -= this.viewportBorder;
  49843. if (away > this.borderLimit) {
  49844. away = this.borderLimit;
  49845. }
  49846. var intensity = 1.0 - (away / this.borderLimit);
  49847. if (intensity < 0) {
  49848. return false;
  49849. }
  49850. if (intensity > 1.0) {
  49851. intensity = 1.0;
  49852. }
  49853. if (this.viewportBorder > 0) {
  49854. globalViewport.x += this.viewportBorder;
  49855. globalViewport.y += this.viewportBorder;
  49856. globalViewport.width -= this.viewportBorder * 2;
  49857. globalViewport.height -= this.viewportBorder * 2;
  49858. this._positionX -= this.viewportBorder;
  49859. this._positionY -= this.viewportBorder;
  49860. }
  49861. // Position
  49862. var centerX = globalViewport.x + globalViewport.width / 2;
  49863. var centerY = globalViewport.y + globalViewport.height / 2;
  49864. var distX = centerX - this._positionX;
  49865. var distY = centerY - this._positionY;
  49866. // Effects
  49867. engine.enableEffect(this._effect);
  49868. engine.setState(false);
  49869. engine.setDepthBuffer(false);
  49870. // VBOs
  49871. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  49872. // Flares
  49873. for (var index = 0; index < this.lensFlares.length; index++) {
  49874. var flare = this.lensFlares[index];
  49875. engine.setAlphaMode(flare.alphaMode);
  49876. var x = centerX - (distX * flare.position);
  49877. var y = centerY - (distY * flare.position);
  49878. var cw = flare.size;
  49879. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  49880. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  49881. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  49882. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  49883. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  49884. // Texture
  49885. this._effect.setTexture("textureSampler", flare.texture);
  49886. // Color
  49887. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  49888. // Draw order
  49889. engine.draw(true, 0, 6);
  49890. }
  49891. engine.setDepthBuffer(true);
  49892. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49893. return true;
  49894. };
  49895. LensFlareSystem.prototype.dispose = function () {
  49896. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  49897. if (vertexBuffer) {
  49898. vertexBuffer.dispose();
  49899. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  49900. }
  49901. if (this._indexBuffer) {
  49902. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49903. this._indexBuffer = null;
  49904. }
  49905. while (this.lensFlares.length) {
  49906. this.lensFlares[0].dispose();
  49907. }
  49908. // Remove from scene
  49909. var index = this._scene.lensFlareSystems.indexOf(this);
  49910. this._scene.lensFlareSystems.splice(index, 1);
  49911. };
  49912. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  49913. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  49914. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  49915. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  49916. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  49917. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  49918. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  49919. var parsedFlare = parsedLensFlareSystem.flares[index];
  49920. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  49921. }
  49922. return lensFlareSystem;
  49923. };
  49924. LensFlareSystem.prototype.serialize = function () {
  49925. var serializationObject = {};
  49926. serializationObject.id = this.id;
  49927. serializationObject.name = this.name;
  49928. serializationObject.emitterId = this.getEmitter().id;
  49929. serializationObject.borderLimit = this.borderLimit;
  49930. serializationObject.flares = [];
  49931. for (var index = 0; index < this.lensFlares.length; index++) {
  49932. var flare = this.lensFlares[index];
  49933. serializationObject.flares.push({
  49934. size: flare.size,
  49935. position: flare.position,
  49936. color: flare.color.asArray(),
  49937. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  49938. });
  49939. }
  49940. return serializationObject;
  49941. };
  49942. return LensFlareSystem;
  49943. }());
  49944. BABYLON.LensFlareSystem = LensFlareSystem;
  49945. })(BABYLON || (BABYLON = {}));
  49946. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  49947. /// <reference path="babylon.freeCamera.ts" />
  49948. var BABYLON;
  49949. (function (BABYLON) {
  49950. // We're mainly based on the logic defined into the FreeCamera code
  49951. var DeviceOrientationCamera = (function (_super) {
  49952. __extends(DeviceOrientationCamera, _super);
  49953. function DeviceOrientationCamera(name, position, scene) {
  49954. var _this = _super.call(this, name, position, scene) || this;
  49955. _this._quaternionCache = new BABYLON.Quaternion();
  49956. _this.inputs.addDeviceOrientation();
  49957. return _this;
  49958. }
  49959. DeviceOrientationCamera.prototype.getClassName = function () {
  49960. return "DeviceOrientationCamera";
  49961. };
  49962. DeviceOrientationCamera.prototype._checkInputs = function () {
  49963. _super.prototype._checkInputs.call(this);
  49964. this._quaternionCache.copyFrom(this.rotationQuaternion);
  49965. if (this._initialQuaternion) {
  49966. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49967. }
  49968. };
  49969. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  49970. var _this = this;
  49971. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  49972. //can only work if this camera has a rotation quaternion already.
  49973. if (!this.rotationQuaternion)
  49974. return;
  49975. if (!this._initialQuaternion) {
  49976. this._initialQuaternion = new BABYLON.Quaternion();
  49977. }
  49978. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  49979. ['x', 'y', 'z'].forEach(function (axisName) {
  49980. if (!axis[axisName]) {
  49981. _this._initialQuaternion[axisName] = 0;
  49982. }
  49983. else {
  49984. _this._initialQuaternion[axisName] *= -1;
  49985. }
  49986. });
  49987. this._initialQuaternion.normalize();
  49988. //force rotation update
  49989. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  49990. };
  49991. return DeviceOrientationCamera;
  49992. }(BABYLON.FreeCamera));
  49993. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  49994. })(BABYLON || (BABYLON = {}));
  49995. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  49996. var BABYLON;
  49997. (function (BABYLON) {
  49998. var VRDeviceOrientationFreeCamera = (function (_super) {
  49999. __extends(VRDeviceOrientationFreeCamera, _super);
  50000. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50001. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50002. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50003. var _this = _super.call(this, name, position, scene) || this;
  50004. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50005. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50006. return _this;
  50007. }
  50008. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  50009. return "VRDeviceOrientationFreeCamera";
  50010. };
  50011. return VRDeviceOrientationFreeCamera;
  50012. }(BABYLON.DeviceOrientationCamera));
  50013. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50014. var VRDeviceOrientationGamepadCamera = (function (_super) {
  50015. __extends(VRDeviceOrientationGamepadCamera, _super);
  50016. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50017. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50018. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50019. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  50020. _this.inputs.addGamepad();
  50021. return _this;
  50022. }
  50023. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  50024. return "VRDeviceOrientationGamepadCamera";
  50025. };
  50026. return VRDeviceOrientationGamepadCamera;
  50027. }(VRDeviceOrientationFreeCamera));
  50028. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  50029. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50030. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50031. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  50032. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50033. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50034. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  50035. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50036. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50037. _this.inputs.addVRDeviceOrientation();
  50038. return _this;
  50039. }
  50040. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  50041. return "VRDeviceOrientationArcRotateCamera";
  50042. };
  50043. return VRDeviceOrientationArcRotateCamera;
  50044. }(BABYLON.ArcRotateCamera));
  50045. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50046. })(BABYLON || (BABYLON = {}));
  50047. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  50048. /// <reference path="babylon.touchCamera.ts" />
  50049. var BABYLON;
  50050. (function (BABYLON) {
  50051. // We're mainly based on the logic defined into the FreeCamera code
  50052. var UniversalCamera = (function (_super) {
  50053. __extends(UniversalCamera, _super);
  50054. //-- end properties for backward compatibility for inputs
  50055. function UniversalCamera(name, position, scene) {
  50056. var _this = _super.call(this, name, position, scene) || this;
  50057. _this.inputs.addGamepad();
  50058. return _this;
  50059. }
  50060. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50061. //-- Begin properties for backward compatibility for inputs
  50062. get: function () {
  50063. var gamepad = this.inputs.attached["gamepad"];
  50064. if (gamepad)
  50065. return gamepad.gamepadAngularSensibility;
  50066. },
  50067. set: function (value) {
  50068. var gamepad = this.inputs.attached["gamepad"];
  50069. if (gamepad)
  50070. gamepad.gamepadAngularSensibility = value;
  50071. },
  50072. enumerable: true,
  50073. configurable: true
  50074. });
  50075. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50076. get: function () {
  50077. var gamepad = this.inputs.attached["gamepad"];
  50078. if (gamepad)
  50079. return gamepad.gamepadMoveSensibility;
  50080. },
  50081. set: function (value) {
  50082. var gamepad = this.inputs.attached["gamepad"];
  50083. if (gamepad)
  50084. gamepad.gamepadMoveSensibility = value;
  50085. },
  50086. enumerable: true,
  50087. configurable: true
  50088. });
  50089. UniversalCamera.prototype.getClassName = function () {
  50090. return "UniversalCamera";
  50091. };
  50092. return UniversalCamera;
  50093. }(BABYLON.TouchCamera));
  50094. BABYLON.UniversalCamera = UniversalCamera;
  50095. })(BABYLON || (BABYLON = {}));
  50096. //# sourceMappingURL=babylon.universalCamera.js.map
  50097. var BABYLON;
  50098. (function (BABYLON) {
  50099. var Gamepads = (function () {
  50100. function Gamepads(ongamedpadconnected) {
  50101. var _this = this;
  50102. this.babylonGamepads = [];
  50103. this.oneGamepadConnected = false;
  50104. this.isMonitoring = false;
  50105. this.gamepadEventSupported = 'GamepadEvent' in window;
  50106. this.gamepadSupport = (navigator.getGamepads ||
  50107. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50108. this._callbackGamepadConnected = ongamedpadconnected;
  50109. if (this.gamepadSupport) {
  50110. //first add already-connected gamepads
  50111. this._updateGamepadObjects();
  50112. if (this.babylonGamepads.length) {
  50113. this._startMonitoringGamepads();
  50114. }
  50115. // Checking if the gamepad connected event is supported (like in Firefox)
  50116. if (this.gamepadEventSupported) {
  50117. this._onGamepadConnectedEvent = function (evt) {
  50118. _this._onGamepadConnected(evt.gamepad);
  50119. };
  50120. this._onGamepadDisonnectedEvent = function (evt) {
  50121. _this._onGamepadDisconnected(evt);
  50122. };
  50123. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50124. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50125. }
  50126. else {
  50127. this._startMonitoringGamepads();
  50128. }
  50129. }
  50130. }
  50131. Gamepads.prototype.dispose = function () {
  50132. if (Gamepads.gamepadDOMInfo) {
  50133. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50134. }
  50135. if (this._onGamepadConnectedEvent) {
  50136. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50137. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50138. this._onGamepadConnectedEvent = null;
  50139. this._onGamepadDisonnectedEvent = null;
  50140. }
  50141. };
  50142. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  50143. var newGamepad = this._addNewGamepad(gamepad);
  50144. if (this._callbackGamepadConnected)
  50145. this._callbackGamepadConnected(newGamepad);
  50146. this._startMonitoringGamepads();
  50147. };
  50148. Gamepads.prototype._addNewGamepad = function (gamepad) {
  50149. if (!this.oneGamepadConnected) {
  50150. this.oneGamepadConnected = true;
  50151. if (Gamepads.gamepadDOMInfo) {
  50152. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50153. Gamepads.gamepadDOMInfo = null;
  50154. }
  50155. }
  50156. var newGamepad;
  50157. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50158. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50159. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50160. }
  50161. else if (gamepad.pose) {
  50162. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50163. }
  50164. else {
  50165. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  50166. }
  50167. this.babylonGamepads.push(newGamepad);
  50168. return newGamepad;
  50169. };
  50170. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  50171. // Remove the gamepad from the list of gamepads to monitor.
  50172. for (var i in this.babylonGamepads) {
  50173. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  50174. this.babylonGamepads.splice(+i, 1);
  50175. break;
  50176. }
  50177. }
  50178. // If no gamepads are left, stop the polling loop.
  50179. if (this.babylonGamepads.length == 0) {
  50180. this._stopMonitoringGamepads();
  50181. }
  50182. };
  50183. Gamepads.prototype._startMonitoringGamepads = function () {
  50184. if (!this.isMonitoring) {
  50185. this.isMonitoring = true;
  50186. this._checkGamepadsStatus();
  50187. }
  50188. };
  50189. Gamepads.prototype._stopMonitoringGamepads = function () {
  50190. this.isMonitoring = false;
  50191. };
  50192. Gamepads.prototype._checkGamepadsStatus = function () {
  50193. var _this = this;
  50194. // updating gamepad objects
  50195. this._updateGamepadObjects();
  50196. for (var i in this.babylonGamepads) {
  50197. this.babylonGamepads[i].update();
  50198. }
  50199. if (this.isMonitoring) {
  50200. if (window.requestAnimationFrame) {
  50201. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50202. }
  50203. else if (window.mozRequestAnimationFrame) {
  50204. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50205. }
  50206. else if (window.webkitRequestAnimationFrame) {
  50207. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  50208. }
  50209. }
  50210. };
  50211. // This function is called only on Chrome, which does not yet support
  50212. // connection/disconnection events, but requires you to monitor
  50213. // an array for changes.
  50214. Gamepads.prototype._updateGamepadObjects = function () {
  50215. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50216. for (var i = 0; i < gamepads.length; i++) {
  50217. if (gamepads[i]) {
  50218. if (!(gamepads[i].index in this.babylonGamepads)) {
  50219. var newGamepad = this._addNewGamepad(gamepads[i]);
  50220. if (this._callbackGamepadConnected) {
  50221. this._callbackGamepadConnected(newGamepad);
  50222. }
  50223. }
  50224. else {
  50225. this.babylonGamepads[i].browserGamepad = gamepads[i];
  50226. }
  50227. }
  50228. }
  50229. };
  50230. return Gamepads;
  50231. }());
  50232. BABYLON.Gamepads = Gamepads;
  50233. var StickValues = (function () {
  50234. function StickValues(x, y) {
  50235. this.x = x;
  50236. this.y = y;
  50237. }
  50238. return StickValues;
  50239. }());
  50240. BABYLON.StickValues = StickValues;
  50241. var Gamepad = (function () {
  50242. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50243. if (leftStickX === void 0) { leftStickX = 0; }
  50244. if (leftStickY === void 0) { leftStickY = 1; }
  50245. if (rightStickX === void 0) { rightStickX = 2; }
  50246. if (rightStickY === void 0) { rightStickY = 3; }
  50247. this.id = id;
  50248. this.index = index;
  50249. this.browserGamepad = browserGamepad;
  50250. this.type = Gamepad.GAMEPAD;
  50251. this._leftStickAxisX = leftStickX;
  50252. this._leftStickAxisY = leftStickY;
  50253. this._rightStickAxisX = rightStickX;
  50254. this._rightStickAxisY = rightStickY;
  50255. if (this.browserGamepad.axes.length >= 2) {
  50256. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50257. }
  50258. if (this.browserGamepad.axes.length >= 4) {
  50259. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50260. }
  50261. }
  50262. Gamepad.prototype.onleftstickchanged = function (callback) {
  50263. this._onleftstickchanged = callback;
  50264. };
  50265. Gamepad.prototype.onrightstickchanged = function (callback) {
  50266. this._onrightstickchanged = callback;
  50267. };
  50268. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50269. get: function () {
  50270. return this._leftStick;
  50271. },
  50272. set: function (newValues) {
  50273. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50274. this._onleftstickchanged(newValues);
  50275. }
  50276. this._leftStick = newValues;
  50277. },
  50278. enumerable: true,
  50279. configurable: true
  50280. });
  50281. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50282. get: function () {
  50283. return this._rightStick;
  50284. },
  50285. set: function (newValues) {
  50286. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50287. this._onrightstickchanged(newValues);
  50288. }
  50289. this._rightStick = newValues;
  50290. },
  50291. enumerable: true,
  50292. configurable: true
  50293. });
  50294. Gamepad.prototype.update = function () {
  50295. if (this._leftStick) {
  50296. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50297. }
  50298. if (this._rightStick) {
  50299. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50300. }
  50301. };
  50302. return Gamepad;
  50303. }());
  50304. Gamepad.GAMEPAD = 0;
  50305. Gamepad.GENERIC = 1;
  50306. Gamepad.XBOX = 2;
  50307. Gamepad.POSE_ENABLED = 3;
  50308. BABYLON.Gamepad = Gamepad;
  50309. var GenericPad = (function (_super) {
  50310. __extends(GenericPad, _super);
  50311. function GenericPad(id, index, gamepad) {
  50312. var _this = _super.call(this, id, index, gamepad) || this;
  50313. _this.id = id;
  50314. _this.index = index;
  50315. _this.gamepad = gamepad;
  50316. _this.type = Gamepad.GENERIC;
  50317. _this._buttons = new Array(gamepad.buttons.length);
  50318. return _this;
  50319. }
  50320. GenericPad.prototype.onbuttondown = function (callback) {
  50321. this._onbuttondown = callback;
  50322. };
  50323. GenericPad.prototype.onbuttonup = function (callback) {
  50324. this._onbuttonup = callback;
  50325. };
  50326. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  50327. if (newValue !== currentValue) {
  50328. if (this._onbuttondown && newValue === 1) {
  50329. this._onbuttondown(buttonIndex);
  50330. }
  50331. if (this._onbuttonup && newValue === 0) {
  50332. this._onbuttonup(buttonIndex);
  50333. }
  50334. }
  50335. return newValue;
  50336. };
  50337. GenericPad.prototype.update = function () {
  50338. _super.prototype.update.call(this);
  50339. for (var index = 0; index < this._buttons.length; index++) {
  50340. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  50341. }
  50342. };
  50343. return GenericPad;
  50344. }(Gamepad));
  50345. BABYLON.GenericPad = GenericPad;
  50346. var Xbox360Button;
  50347. (function (Xbox360Button) {
  50348. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  50349. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  50350. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  50351. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  50352. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  50353. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  50354. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  50355. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  50356. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  50357. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  50358. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  50359. var Xbox360Dpad;
  50360. (function (Xbox360Dpad) {
  50361. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  50362. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  50363. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  50364. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  50365. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  50366. var Xbox360Pad = (function (_super) {
  50367. __extends(Xbox360Pad, _super);
  50368. function Xbox360Pad(id, index, gamepad, xboxOne) {
  50369. if (xboxOne === void 0) { xboxOne = false; }
  50370. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  50371. _this._leftTrigger = 0;
  50372. _this._rightTrigger = 0;
  50373. _this._buttonA = 0;
  50374. _this._buttonB = 0;
  50375. _this._buttonX = 0;
  50376. _this._buttonY = 0;
  50377. _this._buttonBack = 0;
  50378. _this._buttonStart = 0;
  50379. _this._buttonLB = 0;
  50380. _this._buttonRB = 0;
  50381. _this._buttonLeftStick = 0;
  50382. _this._buttonRightStick = 0;
  50383. _this._dPadUp = 0;
  50384. _this._dPadDown = 0;
  50385. _this._dPadLeft = 0;
  50386. _this._dPadRight = 0;
  50387. _this._isXboxOnePad = false;
  50388. _this.type = Gamepad.XBOX;
  50389. _this._isXboxOnePad = xboxOne;
  50390. return _this;
  50391. }
  50392. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  50393. this._onlefttriggerchanged = callback;
  50394. };
  50395. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  50396. this._onrighttriggerchanged = callback;
  50397. };
  50398. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  50399. get: function () {
  50400. return this._leftTrigger;
  50401. },
  50402. set: function (newValue) {
  50403. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  50404. this._onlefttriggerchanged(newValue);
  50405. }
  50406. this._leftTrigger = newValue;
  50407. },
  50408. enumerable: true,
  50409. configurable: true
  50410. });
  50411. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  50412. get: function () {
  50413. return this._rightTrigger;
  50414. },
  50415. set: function (newValue) {
  50416. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  50417. this._onrighttriggerchanged(newValue);
  50418. }
  50419. this._rightTrigger = newValue;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Xbox360Pad.prototype.onbuttondown = function (callback) {
  50425. this._onbuttondown = callback;
  50426. };
  50427. Xbox360Pad.prototype.onbuttonup = function (callback) {
  50428. this._onbuttonup = callback;
  50429. };
  50430. Xbox360Pad.prototype.ondpaddown = function (callback) {
  50431. this._ondpaddown = callback;
  50432. };
  50433. Xbox360Pad.prototype.ondpadup = function (callback) {
  50434. this._ondpadup = callback;
  50435. };
  50436. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  50437. if (newValue !== currentValue) {
  50438. if (this._onbuttondown && newValue === 1) {
  50439. this._onbuttondown(buttonType);
  50440. }
  50441. if (this._onbuttonup && newValue === 0) {
  50442. this._onbuttonup(buttonType);
  50443. }
  50444. }
  50445. return newValue;
  50446. };
  50447. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  50448. if (newValue !== currentValue) {
  50449. if (this._ondpaddown && newValue === 1) {
  50450. this._ondpaddown(buttonType);
  50451. }
  50452. if (this._ondpadup && newValue === 0) {
  50453. this._ondpadup(buttonType);
  50454. }
  50455. }
  50456. return newValue;
  50457. };
  50458. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  50459. get: function () {
  50460. return this._buttonA;
  50461. },
  50462. set: function (value) {
  50463. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  50464. },
  50465. enumerable: true,
  50466. configurable: true
  50467. });
  50468. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  50469. get: function () {
  50470. return this._buttonB;
  50471. },
  50472. set: function (value) {
  50473. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  50474. },
  50475. enumerable: true,
  50476. configurable: true
  50477. });
  50478. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  50479. get: function () {
  50480. return this._buttonX;
  50481. },
  50482. set: function (value) {
  50483. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  50484. },
  50485. enumerable: true,
  50486. configurable: true
  50487. });
  50488. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  50489. get: function () {
  50490. return this._buttonY;
  50491. },
  50492. set: function (value) {
  50493. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  50494. },
  50495. enumerable: true,
  50496. configurable: true
  50497. });
  50498. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  50499. get: function () {
  50500. return this._buttonStart;
  50501. },
  50502. set: function (value) {
  50503. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  50504. },
  50505. enumerable: true,
  50506. configurable: true
  50507. });
  50508. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  50509. get: function () {
  50510. return this._buttonBack;
  50511. },
  50512. set: function (value) {
  50513. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  50514. },
  50515. enumerable: true,
  50516. configurable: true
  50517. });
  50518. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  50519. get: function () {
  50520. return this._buttonLB;
  50521. },
  50522. set: function (value) {
  50523. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  50524. },
  50525. enumerable: true,
  50526. configurable: true
  50527. });
  50528. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  50529. get: function () {
  50530. return this._buttonRB;
  50531. },
  50532. set: function (value) {
  50533. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  50534. },
  50535. enumerable: true,
  50536. configurable: true
  50537. });
  50538. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  50539. get: function () {
  50540. return this._buttonLeftStick;
  50541. },
  50542. set: function (value) {
  50543. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  50544. },
  50545. enumerable: true,
  50546. configurable: true
  50547. });
  50548. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  50549. get: function () {
  50550. return this._buttonRightStick;
  50551. },
  50552. set: function (value) {
  50553. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  50554. },
  50555. enumerable: true,
  50556. configurable: true
  50557. });
  50558. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  50559. get: function () {
  50560. return this._dPadUp;
  50561. },
  50562. set: function (value) {
  50563. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  50564. },
  50565. enumerable: true,
  50566. configurable: true
  50567. });
  50568. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  50569. get: function () {
  50570. return this._dPadDown;
  50571. },
  50572. set: function (value) {
  50573. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  50574. },
  50575. enumerable: true,
  50576. configurable: true
  50577. });
  50578. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  50579. get: function () {
  50580. return this._dPadLeft;
  50581. },
  50582. set: function (value) {
  50583. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  50584. },
  50585. enumerable: true,
  50586. configurable: true
  50587. });
  50588. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  50589. get: function () {
  50590. return this._dPadRight;
  50591. },
  50592. set: function (value) {
  50593. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  50594. },
  50595. enumerable: true,
  50596. configurable: true
  50597. });
  50598. Xbox360Pad.prototype.update = function () {
  50599. _super.prototype.update.call(this);
  50600. if (this._isXboxOnePad) {
  50601. this.buttonA = this.browserGamepad.buttons[0].value;
  50602. this.buttonB = this.browserGamepad.buttons[1].value;
  50603. this.buttonX = this.browserGamepad.buttons[2].value;
  50604. this.buttonY = this.browserGamepad.buttons[3].value;
  50605. this.buttonLB = this.browserGamepad.buttons[4].value;
  50606. this.buttonRB = this.browserGamepad.buttons[5].value;
  50607. this.leftTrigger = this.browserGamepad.axes[2];
  50608. this.rightTrigger = this.browserGamepad.axes[5];
  50609. this.buttonBack = this.browserGamepad.buttons[9].value;
  50610. this.buttonStart = this.browserGamepad.buttons[8].value;
  50611. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  50612. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  50613. this.dPadUp = this.browserGamepad.buttons[11].value;
  50614. this.dPadDown = this.browserGamepad.buttons[12].value;
  50615. this.dPadLeft = this.browserGamepad.buttons[13].value;
  50616. this.dPadRight = this.browserGamepad.buttons[14].value;
  50617. }
  50618. else {
  50619. this.buttonA = this.browserGamepad.buttons[0].value;
  50620. this.buttonB = this.browserGamepad.buttons[1].value;
  50621. this.buttonX = this.browserGamepad.buttons[2].value;
  50622. this.buttonY = this.browserGamepad.buttons[3].value;
  50623. this.buttonLB = this.browserGamepad.buttons[4].value;
  50624. this.buttonRB = this.browserGamepad.buttons[5].value;
  50625. this.leftTrigger = this.browserGamepad.buttons[6].value;
  50626. this.rightTrigger = this.browserGamepad.buttons[7].value;
  50627. this.buttonBack = this.browserGamepad.buttons[8].value;
  50628. this.buttonStart = this.browserGamepad.buttons[9].value;
  50629. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  50630. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  50631. this.dPadUp = this.browserGamepad.buttons[12].value;
  50632. this.dPadDown = this.browserGamepad.buttons[13].value;
  50633. this.dPadLeft = this.browserGamepad.buttons[14].value;
  50634. this.dPadRight = this.browserGamepad.buttons[15].value;
  50635. }
  50636. };
  50637. return Xbox360Pad;
  50638. }(Gamepad));
  50639. BABYLON.Xbox360Pad = Xbox360Pad;
  50640. })(BABYLON || (BABYLON = {}));
  50641. //# sourceMappingURL=babylon.gamepads.js.map
  50642. var BABYLON;
  50643. (function (BABYLON) {
  50644. var PoseEnabledControllerType;
  50645. (function (PoseEnabledControllerType) {
  50646. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  50647. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  50648. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  50649. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  50650. var PoseEnabledControllerHelper = (function () {
  50651. function PoseEnabledControllerHelper() {
  50652. }
  50653. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  50654. // for now, only Oculus and Vive are supported
  50655. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  50656. return new OculusTouchController(vrGamepad);
  50657. }
  50658. else {
  50659. return new ViveController(vrGamepad);
  50660. }
  50661. };
  50662. return PoseEnabledControllerHelper;
  50663. }());
  50664. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  50665. var PoseEnabledController = (function (_super) {
  50666. __extends(PoseEnabledController, _super);
  50667. function PoseEnabledController(vrGamepad) {
  50668. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  50669. _this.vrGamepad = vrGamepad;
  50670. _this.deviceScaleFactor = 1;
  50671. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  50672. _this.controllerType = PoseEnabledControllerType.GENERIC;
  50673. _this.position = BABYLON.Vector3.Zero();
  50674. _this.rotationQuaternion = new BABYLON.Quaternion();
  50675. _this.devicePosition = BABYLON.Vector3.Zero();
  50676. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50677. _this._calculatedPosition = BABYLON.Vector3.Zero();
  50678. _this._calculatedRotation = new BABYLON.Quaternion();
  50679. return _this;
  50680. }
  50681. PoseEnabledController.prototype.update = function () {
  50682. _super.prototype.update.call(this);
  50683. // update this device's offset position from the attached camera, if provided
  50684. if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  50685. //this.position.copyFrom(this._poseControlledCamera.position);
  50686. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  50687. this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  50688. }
  50689. var pose = this.vrGamepad.pose;
  50690. this.updateFromDevice(pose);
  50691. if (this._mesh) {
  50692. this._mesh.position.copyFrom(this._calculatedPosition);
  50693. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  50694. }
  50695. };
  50696. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  50697. if (poseData) {
  50698. this.rawPose = poseData;
  50699. if (poseData.position) {
  50700. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  50701. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50702. this.devicePosition.z *= -1;
  50703. }
  50704. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  50705. this._calculatedPosition.addInPlace(this.position);
  50706. // scale the position using the scale factor, add the device's position
  50707. if (this._poseControlledCamera) {
  50708. // this allows total positioning freedom - the device, the camera and the mesh can be individually controlled.
  50709. this._calculatedPosition.addInPlace(this._poseControlledCamera.position);
  50710. }
  50711. }
  50712. if (poseData.orientation) {
  50713. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50714. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50715. this.deviceRotationQuaternion.z *= -1;
  50716. this.deviceRotationQuaternion.w *= -1;
  50717. }
  50718. // if the camera is set, rotate to the camera's rotation
  50719. this.rotationQuaternion.multiplyToRef(this.deviceRotationQuaternion, this._calculatedRotation);
  50720. if (this._poseControlledCamera) {
  50721. this._calculatedRotation.multiplyToRef(this._poseControlledCamera.rotationQuaternion, this._calculatedRotation);
  50722. }
  50723. }
  50724. }
  50725. };
  50726. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  50727. this._mesh = mesh;
  50728. if (!this._mesh.rotationQuaternion) {
  50729. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  50730. }
  50731. };
  50732. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  50733. this._poseControlledCamera = camera;
  50734. this.deviceScaleFactor = camera.deviceScaleFactor;
  50735. };
  50736. PoseEnabledController.prototype.detachMesh = function () {
  50737. this._mesh = undefined;
  50738. };
  50739. return PoseEnabledController;
  50740. }(BABYLON.Gamepad));
  50741. BABYLON.PoseEnabledController = PoseEnabledController;
  50742. var WebVRController = (function (_super) {
  50743. __extends(WebVRController, _super);
  50744. function WebVRController(vrGamepad) {
  50745. var _this = _super.call(this, vrGamepad) || this;
  50746. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  50747. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  50748. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  50749. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  50750. _this.onPadStateChangedObservable = new BABYLON.Observable();
  50751. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  50752. _this.pad = { x: 0, y: 0 };
  50753. // avoid GC, store state in a tmp object
  50754. _this._changes = {
  50755. pressChanged: false,
  50756. touchChanged: false,
  50757. valueChanged: false,
  50758. changed: false
  50759. };
  50760. _this._buttons = new Array(vrGamepad.buttons.length);
  50761. _this.hand = vrGamepad.hand;
  50762. return _this;
  50763. }
  50764. WebVRController.prototype.onButtonStateChange = function (callback) {
  50765. this._onButtonStateChange = callback;
  50766. };
  50767. WebVRController.prototype.update = function () {
  50768. _super.prototype.update.call(this);
  50769. for (var index = 0; index < this._buttons.length; index++) {
  50770. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  50771. }
  50772. ;
  50773. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  50774. this.pad.x = this.leftStick.x;
  50775. this.pad.y = this.leftStick.y;
  50776. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  50777. }
  50778. };
  50779. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  50780. if (!currentState) {
  50781. this._buttons[buttonIndex] = {
  50782. pressed: newState.pressed,
  50783. touched: newState.touched,
  50784. value: newState.value
  50785. };
  50786. return;
  50787. }
  50788. this._checkChanges(newState, currentState);
  50789. if (this._changes.changed) {
  50790. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  50791. this.handleButtonChange(buttonIndex, newState, this._changes);
  50792. }
  50793. this._buttons[buttonIndex].pressed = newState.pressed;
  50794. this._buttons[buttonIndex].touched = newState.touched;
  50795. // oculus triggers are never 0, thou not touched.
  50796. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  50797. };
  50798. WebVRController.prototype._checkChanges = function (newState, currentState) {
  50799. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  50800. this._changes.touchChanged = newState.touched !== currentState.touched;
  50801. this._changes.valueChanged = newState.value !== currentState.value;
  50802. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  50803. return this._changes;
  50804. };
  50805. return WebVRController;
  50806. }(PoseEnabledController));
  50807. BABYLON.WebVRController = WebVRController;
  50808. var OculusTouchController = (function (_super) {
  50809. __extends(OculusTouchController, _super);
  50810. function OculusTouchController(vrGamepad) {
  50811. var _this = _super.call(this, vrGamepad) || this;
  50812. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  50813. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  50814. _this.controllerType = PoseEnabledControllerType.OCULUS;
  50815. return _this;
  50816. }
  50817. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  50818. // helper getters for left and right hand.
  50819. get: function () {
  50820. if (this.hand === 'right') {
  50821. return this.onMainButtonStateChangedObservable;
  50822. }
  50823. else {
  50824. throw new Error('No A button on left hand');
  50825. }
  50826. },
  50827. enumerable: true,
  50828. configurable: true
  50829. });
  50830. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  50831. get: function () {
  50832. if (this.hand === 'right') {
  50833. return this.onSecondaryButtonStateChangedObservable;
  50834. }
  50835. else {
  50836. throw new Error('No B button on left hand');
  50837. }
  50838. },
  50839. enumerable: true,
  50840. configurable: true
  50841. });
  50842. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  50843. get: function () {
  50844. if (this.hand === 'left') {
  50845. return this.onMainButtonStateChangedObservable;
  50846. }
  50847. else {
  50848. throw new Error('No X button on right hand');
  50849. }
  50850. },
  50851. enumerable: true,
  50852. configurable: true
  50853. });
  50854. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  50855. get: function () {
  50856. if (this.hand === 'left') {
  50857. return this.onSecondaryButtonStateChangedObservable;
  50858. }
  50859. else {
  50860. throw new Error('No Y button on right hand');
  50861. }
  50862. },
  50863. enumerable: true,
  50864. configurable: true
  50865. });
  50866. /*
  50867. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  50868. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  50869. 2) secondary trigger (same)
  50870. 3) A (right) X (left), touch, pressed = value
  50871. 4) B / Y
  50872. 5) thumb rest
  50873. */
  50874. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50875. var notifyObject = state; //{ state: state, changes: changes };
  50876. switch (buttonIdx) {
  50877. case 0:
  50878. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50879. return;
  50880. case 1:
  50881. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50882. return;
  50883. case 2:
  50884. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  50885. return;
  50886. case 3:
  50887. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50888. return;
  50889. case 4:
  50890. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50891. return;
  50892. case 5:
  50893. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  50894. return;
  50895. }
  50896. };
  50897. return OculusTouchController;
  50898. }(WebVRController));
  50899. BABYLON.OculusTouchController = OculusTouchController;
  50900. var ViveController = (function (_super) {
  50901. __extends(ViveController, _super);
  50902. function ViveController(vrGamepad) {
  50903. var _this = _super.call(this, vrGamepad) || this;
  50904. _this.controllerType = PoseEnabledControllerType.VIVE;
  50905. return _this;
  50906. }
  50907. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  50908. get: function () {
  50909. return this.onMainButtonStateChangedObservable;
  50910. },
  50911. enumerable: true,
  50912. configurable: true
  50913. });
  50914. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  50915. get: function () {
  50916. return this.onMainButtonStateChangedObservable;
  50917. },
  50918. enumerable: true,
  50919. configurable: true
  50920. });
  50921. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  50922. get: function () {
  50923. return this.onSecondaryButtonStateChangedObservable;
  50924. },
  50925. enumerable: true,
  50926. configurable: true
  50927. });
  50928. /**
  50929. * Vive mapping:
  50930. * 0: touchpad
  50931. * 1: trigger
  50932. * 2: left AND right buttons
  50933. * 3: menu button
  50934. */
  50935. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  50936. var notifyObject = state; //{ state: state, changes: changes };
  50937. switch (buttonIdx) {
  50938. case 0:
  50939. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  50940. return;
  50941. case 1:
  50942. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  50943. return;
  50944. case 2:
  50945. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  50946. return;
  50947. case 3:
  50948. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  50949. return;
  50950. }
  50951. };
  50952. return ViveController;
  50953. }(WebVRController));
  50954. BABYLON.ViveController = ViveController;
  50955. })(BABYLON || (BABYLON = {}));
  50956. //# sourceMappingURL=babylon.extendedGamepad.js.map
  50957. /// <reference path="babylon.universalCamera.ts" />
  50958. var BABYLON;
  50959. (function (BABYLON) {
  50960. // We're mainly based on the logic defined into the FreeCamera code
  50961. var GamepadCamera = (function (_super) {
  50962. __extends(GamepadCamera, _super);
  50963. //-- end properties for backward compatibility for inputs
  50964. function GamepadCamera(name, position, scene) {
  50965. return _super.call(this, name, position, scene) || this;
  50966. }
  50967. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  50968. //-- Begin properties for backward compatibility for inputs
  50969. get: function () {
  50970. var gamepad = this.inputs.attached["gamepad"];
  50971. if (gamepad)
  50972. return gamepad.gamepadAngularSensibility;
  50973. },
  50974. set: function (value) {
  50975. var gamepad = this.inputs.attached["gamepad"];
  50976. if (gamepad)
  50977. gamepad.gamepadAngularSensibility = value;
  50978. },
  50979. enumerable: true,
  50980. configurable: true
  50981. });
  50982. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  50983. get: function () {
  50984. var gamepad = this.inputs.attached["gamepad"];
  50985. if (gamepad)
  50986. return gamepad.gamepadMoveSensibility;
  50987. },
  50988. set: function (value) {
  50989. var gamepad = this.inputs.attached["gamepad"];
  50990. if (gamepad)
  50991. gamepad.gamepadMoveSensibility = value;
  50992. },
  50993. enumerable: true,
  50994. configurable: true
  50995. });
  50996. GamepadCamera.prototype.getClassName = function () {
  50997. return "GamepadCamera";
  50998. };
  50999. return GamepadCamera;
  51000. }(BABYLON.UniversalCamera));
  51001. BABYLON.GamepadCamera = GamepadCamera;
  51002. })(BABYLON || (BABYLON = {}));
  51003. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51004. var BABYLON;
  51005. (function (BABYLON) {
  51006. var Analyser = (function () {
  51007. function Analyser(scene) {
  51008. this.SMOOTHING = 0.75;
  51009. this.FFT_SIZE = 512;
  51010. this.BARGRAPHAMPLITUDE = 256;
  51011. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51012. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51013. this._scene = scene;
  51014. this._audioEngine = BABYLON.Engine.audioEngine;
  51015. if (this._audioEngine.canUseWebAudio) {
  51016. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51017. this._webAudioAnalyser.minDecibels = -140;
  51018. this._webAudioAnalyser.maxDecibels = 0;
  51019. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51020. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51021. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51022. }
  51023. }
  51024. Analyser.prototype.getFrequencyBinCount = function () {
  51025. if (this._audioEngine.canUseWebAudio) {
  51026. return this._webAudioAnalyser.frequencyBinCount;
  51027. }
  51028. else {
  51029. return 0;
  51030. }
  51031. };
  51032. Analyser.prototype.getByteFrequencyData = function () {
  51033. if (this._audioEngine.canUseWebAudio) {
  51034. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51035. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51036. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51037. }
  51038. return this._byteFreqs;
  51039. };
  51040. Analyser.prototype.getByteTimeDomainData = function () {
  51041. if (this._audioEngine.canUseWebAudio) {
  51042. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51043. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51044. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51045. }
  51046. return this._byteTime;
  51047. };
  51048. Analyser.prototype.getFloatFrequencyData = function () {
  51049. if (this._audioEngine.canUseWebAudio) {
  51050. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51051. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51052. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51053. }
  51054. return this._floatFreqs;
  51055. };
  51056. Analyser.prototype.drawDebugCanvas = function () {
  51057. var _this = this;
  51058. if (this._audioEngine.canUseWebAudio) {
  51059. if (!this._debugCanvas) {
  51060. this._debugCanvas = document.createElement("canvas");
  51061. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51062. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51063. this._debugCanvas.style.position = "absolute";
  51064. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51065. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51066. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51067. document.body.appendChild(this._debugCanvas);
  51068. this._registerFunc = function () {
  51069. _this.drawDebugCanvas();
  51070. };
  51071. this._scene.registerBeforeRender(this._registerFunc);
  51072. }
  51073. if (this._registerFunc) {
  51074. var workingArray = this.getByteFrequencyData();
  51075. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51076. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51077. // Draw the frequency domain chart.
  51078. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51079. var value = workingArray[i];
  51080. var percent = value / this.BARGRAPHAMPLITUDE;
  51081. var height = this.DEBUGCANVASSIZE.height * percent;
  51082. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51083. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51084. var hue = i / this.getFrequencyBinCount() * 360;
  51085. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51086. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51087. }
  51088. }
  51089. }
  51090. };
  51091. Analyser.prototype.stopDebugCanvas = function () {
  51092. if (this._debugCanvas) {
  51093. this._scene.unregisterBeforeRender(this._registerFunc);
  51094. this._registerFunc = null;
  51095. document.body.removeChild(this._debugCanvas);
  51096. this._debugCanvas = null;
  51097. this._debugCanvasContext = null;
  51098. }
  51099. };
  51100. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51101. if (this._audioEngine.canUseWebAudio) {
  51102. inputAudioNode.connect(this._webAudioAnalyser);
  51103. this._webAudioAnalyser.connect(outputAudioNode);
  51104. }
  51105. };
  51106. Analyser.prototype.dispose = function () {
  51107. if (this._audioEngine.canUseWebAudio) {
  51108. this._webAudioAnalyser.disconnect();
  51109. }
  51110. };
  51111. return Analyser;
  51112. }());
  51113. BABYLON.Analyser = Analyser;
  51114. })(BABYLON || (BABYLON = {}));
  51115. //# sourceMappingURL=babylon.analyser.js.map
  51116. var BABYLON;
  51117. (function (BABYLON) {
  51118. var DepthRenderer = (function () {
  51119. function DepthRenderer(scene, type) {
  51120. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51121. var _this = this;
  51122. this._viewMatrix = BABYLON.Matrix.Zero();
  51123. this._projectionMatrix = BABYLON.Matrix.Zero();
  51124. this._transformMatrix = BABYLON.Matrix.Zero();
  51125. this._worldViewProjection = BABYLON.Matrix.Zero();
  51126. this._scene = scene;
  51127. var engine = scene.getEngine();
  51128. // Render target
  51129. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51130. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51131. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51132. this._depthMap.refreshRate = 1;
  51133. this._depthMap.renderParticles = false;
  51134. this._depthMap.renderList = null;
  51135. // set default depth value to 1.0 (far away)
  51136. this._depthMap.onClearObservable.add(function (engine) {
  51137. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51138. });
  51139. // Custom render function
  51140. var renderSubMesh = function (subMesh) {
  51141. var mesh = subMesh.getRenderingMesh();
  51142. var scene = _this._scene;
  51143. var engine = scene.getEngine();
  51144. // Culling
  51145. engine.setState(subMesh.getMaterial().backFaceCulling);
  51146. // Managing instances
  51147. var batch = mesh._getInstancesRenderList(subMesh._id);
  51148. if (batch.mustReturn) {
  51149. return;
  51150. }
  51151. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51152. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51153. engine.enableEffect(_this._effect);
  51154. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  51155. var material = subMesh.getMaterial();
  51156. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  51157. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  51158. // Alpha test
  51159. if (material && material.needAlphaTesting()) {
  51160. var alphaTexture = material.getAlphaTestTexture();
  51161. _this._effect.setTexture("diffuseSampler", alphaTexture);
  51162. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51163. }
  51164. // Bones
  51165. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51166. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51167. }
  51168. // Draw
  51169. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51170. }
  51171. };
  51172. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  51173. var index;
  51174. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51175. renderSubMesh(opaqueSubMeshes.data[index]);
  51176. }
  51177. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51178. renderSubMesh(alphaTestSubMeshes.data[index]);
  51179. }
  51180. };
  51181. }
  51182. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  51183. var material = subMesh.getMaterial();
  51184. if (material.disableDepthWrite) {
  51185. return false;
  51186. }
  51187. var defines = [];
  51188. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51189. var mesh = subMesh.getMesh();
  51190. var scene = mesh.getScene();
  51191. // Alpha test
  51192. if (material && material.needAlphaTesting()) {
  51193. defines.push("#define ALPHATEST");
  51194. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51195. attribs.push(BABYLON.VertexBuffer.UVKind);
  51196. defines.push("#define UV1");
  51197. }
  51198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51199. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51200. defines.push("#define UV2");
  51201. }
  51202. }
  51203. // Bones
  51204. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51207. if (mesh.numBoneInfluencers > 4) {
  51208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51210. }
  51211. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51212. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51213. }
  51214. else {
  51215. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51216. }
  51217. // Instances
  51218. if (useInstances) {
  51219. defines.push("#define INSTANCES");
  51220. attribs.push("world0");
  51221. attribs.push("world1");
  51222. attribs.push("world2");
  51223. attribs.push("world3");
  51224. }
  51225. // Get correct effect
  51226. var join = defines.join("\n");
  51227. if (this._cachedDefines !== join) {
  51228. this._cachedDefines = join;
  51229. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  51230. }
  51231. return this._effect.isReady();
  51232. };
  51233. DepthRenderer.prototype.getDepthMap = function () {
  51234. return this._depthMap;
  51235. };
  51236. // Methods
  51237. DepthRenderer.prototype.dispose = function () {
  51238. this._depthMap.dispose();
  51239. };
  51240. return DepthRenderer;
  51241. }());
  51242. BABYLON.DepthRenderer = DepthRenderer;
  51243. })(BABYLON || (BABYLON = {}));
  51244. //# sourceMappingURL=babylon.depthRenderer.js.map
  51245. var BABYLON;
  51246. (function (BABYLON) {
  51247. var SSAORenderingPipeline = (function (_super) {
  51248. __extends(SSAORenderingPipeline, _super);
  51249. /**
  51250. * @constructor
  51251. * @param {string} name - The rendering pipeline name
  51252. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51253. * @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 }
  51254. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51255. */
  51256. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  51257. var _this = _super.call(this, scene.getEngine(), name) || this;
  51258. // Members
  51259. /**
  51260. * The PassPostProcess id in the pipeline that contains the original scene color
  51261. * @type {string}
  51262. */
  51263. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  51264. /**
  51265. * The SSAO PostProcess id in the pipeline
  51266. * @type {string}
  51267. */
  51268. _this.SSAORenderEffect = "SSAORenderEffect";
  51269. /**
  51270. * The horizontal blur PostProcess id in the pipeline
  51271. * @type {string}
  51272. */
  51273. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  51274. /**
  51275. * The vertical blur PostProcess id in the pipeline
  51276. * @type {string}
  51277. */
  51278. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  51279. /**
  51280. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  51281. * @type {string}
  51282. */
  51283. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  51284. /**
  51285. * The output strength of the SSAO post-process. Default value is 1.0.
  51286. * @type {number}
  51287. */
  51288. _this.totalStrength = 1.0;
  51289. /**
  51290. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  51291. * @type {number}
  51292. */
  51293. _this.radius = 0.0001;
  51294. /**
  51295. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  51296. * Must not be equal to fallOff and superior to fallOff.
  51297. * Default value is 0.975
  51298. * @type {number}
  51299. */
  51300. _this.area = 0.0075;
  51301. /**
  51302. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  51303. * Must not be equal to area and inferior to area.
  51304. * Default value is 0.0
  51305. * @type {number}
  51306. */
  51307. _this.fallOff = 0.000001;
  51308. /**
  51309. * The base color of the SSAO post-process
  51310. * The final result is "base + ssao" between [0, 1]
  51311. * @type {number}
  51312. */
  51313. _this.base = 0.5;
  51314. _this._firstUpdate = true;
  51315. _this._scene = scene;
  51316. // Set up assets
  51317. _this._createRandomTexture();
  51318. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51319. var ssaoRatio = ratio.ssaoRatio || ratio;
  51320. var combineRatio = ratio.combineRatio || ratio;
  51321. _this._ratio = {
  51322. ssaoRatio: ssaoRatio,
  51323. combineRatio: combineRatio
  51324. };
  51325. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  51326. _this._createSSAOPostProcess(ssaoRatio);
  51327. _this._createBlurPostProcess(ssaoRatio);
  51328. _this._createSSAOCombinePostProcess(combineRatio);
  51329. // Set up pipeline
  51330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  51331. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  51332. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  51333. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  51334. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  51335. // Finish
  51336. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51337. if (cameras)
  51338. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51339. return _this;
  51340. }
  51341. // Public Methods
  51342. /**
  51343. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  51344. */
  51345. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51346. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51347. for (var i = 0; i < this._scene.cameras.length; i++) {
  51348. var camera = this._scene.cameras[i];
  51349. this._originalColorPostProcess.dispose(camera);
  51350. this._ssaoPostProcess.dispose(camera);
  51351. this._blurHPostProcess.dispose(camera);
  51352. this._blurVPostProcess.dispose(camera);
  51353. this._ssaoCombinePostProcess.dispose(camera);
  51354. }
  51355. this._randomTexture.dispose();
  51356. if (disableDepthRender)
  51357. this._scene.disableDepthRenderer();
  51358. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51359. _super.prototype.dispose.call(this);
  51360. };
  51361. // Private Methods
  51362. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  51363. var _this = this;
  51364. /*
  51365. var samplerOffsets = [
  51366. -8.0, -6.0, -4.0, -2.0,
  51367. 0.0,
  51368. 2.0, 4.0, 6.0, 8.0
  51369. ];
  51370. */
  51371. var samples = 16;
  51372. var samplerOffsets = [];
  51373. for (var i = -8; i < 8; i++) {
  51374. samplerOffsets.push(i * 2);
  51375. }
  51376. 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");
  51377. this._blurHPostProcess.onApply = function (effect) {
  51378. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  51379. effect.setTexture("depthSampler", _this._depthTexture);
  51380. if (_this._firstUpdate) {
  51381. effect.setArray("samplerOffsets", samplerOffsets);
  51382. }
  51383. };
  51384. 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");
  51385. this._blurVPostProcess.onApply = function (effect) {
  51386. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  51387. effect.setTexture("depthSampler", _this._depthTexture);
  51388. if (_this._firstUpdate) {
  51389. effect.setArray("samplerOffsets", samplerOffsets);
  51390. _this._firstUpdate = false;
  51391. }
  51392. };
  51393. };
  51394. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  51395. var _this = this;
  51396. var numSamples = 16;
  51397. var sampleSphere = [
  51398. 0.5381, 0.1856, -0.4319,
  51399. 0.1379, 0.2486, 0.4430,
  51400. 0.3371, 0.5679, -0.0057,
  51401. -0.6999, -0.0451, -0.0019,
  51402. 0.0689, -0.1598, -0.8547,
  51403. 0.0560, 0.0069, -0.1843,
  51404. -0.0146, 0.1402, 0.0762,
  51405. 0.0100, -0.1924, -0.0344,
  51406. -0.3577, -0.5301, -0.4358,
  51407. -0.3169, 0.1063, 0.0158,
  51408. 0.0103, -0.5869, 0.0046,
  51409. -0.0897, -0.4940, 0.3287,
  51410. 0.7119, -0.0154, -0.0918,
  51411. -0.0533, 0.0596, -0.5411,
  51412. 0.0352, -0.0631, 0.5460,
  51413. -0.4776, 0.2847, -0.0271
  51414. ];
  51415. var samplesFactor = 1.0 / numSamples;
  51416. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  51417. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  51418. "area", "fallOff", "base", "range", "viewport"
  51419. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  51420. var viewport = new BABYLON.Vector2(0, 0);
  51421. this._ssaoPostProcess.onApply = function (effect) {
  51422. if (_this._firstUpdate) {
  51423. effect.setArray3("sampleSphere", sampleSphere);
  51424. effect.setFloat("samplesFactor", samplesFactor);
  51425. effect.setFloat("randTextureTiles", 4.0);
  51426. }
  51427. effect.setFloat("totalStrength", _this.totalStrength);
  51428. effect.setFloat("radius", _this.radius);
  51429. effect.setFloat("area", _this.area);
  51430. effect.setFloat("fallOff", _this.fallOff);
  51431. effect.setFloat("base", _this.base);
  51432. effect.setTexture("textureSampler", _this._depthTexture);
  51433. effect.setTexture("randomSampler", _this._randomTexture);
  51434. };
  51435. };
  51436. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  51437. var _this = this;
  51438. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  51439. this._ssaoCombinePostProcess.onApply = function (effect) {
  51440. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  51441. };
  51442. };
  51443. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  51444. var size = 512;
  51445. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  51446. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51447. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51448. var context = this._randomTexture.getContext();
  51449. var rand = function (min, max) {
  51450. return Math.random() * (max - min) + min;
  51451. };
  51452. var randVector = BABYLON.Vector3.Zero();
  51453. for (var x = 0; x < size; x++) {
  51454. for (var y = 0; y < size; y++) {
  51455. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  51456. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  51457. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  51458. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  51459. context.fillRect(x, y, 1, 1);
  51460. }
  51461. }
  51462. this._randomTexture.update(false);
  51463. };
  51464. return SSAORenderingPipeline;
  51465. }(BABYLON.PostProcessRenderPipeline));
  51466. __decorate([
  51467. BABYLON.serialize()
  51468. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  51469. __decorate([
  51470. BABYLON.serialize()
  51471. ], SSAORenderingPipeline.prototype, "radius", void 0);
  51472. __decorate([
  51473. BABYLON.serialize()
  51474. ], SSAORenderingPipeline.prototype, "area", void 0);
  51475. __decorate([
  51476. BABYLON.serialize()
  51477. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  51478. __decorate([
  51479. BABYLON.serialize()
  51480. ], SSAORenderingPipeline.prototype, "base", void 0);
  51481. __decorate([
  51482. BABYLON.serialize()
  51483. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  51484. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  51485. })(BABYLON || (BABYLON = {}));
  51486. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  51487. var BABYLON;
  51488. (function (BABYLON) {
  51489. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  51490. var VolumetricLightScatteringPostProcess = (function (_super) {
  51491. __extends(VolumetricLightScatteringPostProcess, _super);
  51492. /**
  51493. * @constructor
  51494. * @param {string} name - The post-process name
  51495. * @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)
  51496. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  51497. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  51498. * @param {number} samples - The post-process quality, default 100
  51499. * @param {number} samplingMode - The post-process filtering mode
  51500. * @param {BABYLON.Engine} engine - The babylon engine
  51501. * @param {boolean} reusable - If the post-process is reusable
  51502. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  51503. */
  51504. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  51505. if (samples === void 0) { samples = 100; }
  51506. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51507. 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;
  51508. _this._screenCoordinates = BABYLON.Vector2.Zero();
  51509. /**
  51510. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  51511. * @type {Vector3}
  51512. */
  51513. _this.customMeshPosition = BABYLON.Vector3.Zero();
  51514. /**
  51515. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  51516. * @type {boolean}
  51517. */
  51518. _this.useCustomMeshPosition = false;
  51519. /**
  51520. * If the post-process should inverse the light scattering direction
  51521. * @type {boolean}
  51522. */
  51523. _this.invert = true;
  51524. /**
  51525. * Array containing the excluded meshes not rendered in the internal pass
  51526. */
  51527. _this.excludedMeshes = new Array();
  51528. /**
  51529. * Controls the overall intensity of the post-process
  51530. * @type {number}
  51531. */
  51532. _this.exposure = 0.3;
  51533. /**
  51534. * Dissipates each sample's contribution in range [0, 1]
  51535. * @type {number}
  51536. */
  51537. _this.decay = 0.96815;
  51538. /**
  51539. * Controls the overall intensity of each sample
  51540. * @type {number}
  51541. */
  51542. _this.weight = 0.58767;
  51543. /**
  51544. * Controls the density of each sample
  51545. * @type {number}
  51546. */
  51547. _this.density = 0.926;
  51548. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  51549. var engine = scene.getEngine();
  51550. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  51551. // Configure mesh
  51552. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  51553. // Configure
  51554. _this._createPass(scene, ratio.passRatio || ratio);
  51555. _this.onActivate = function (camera) {
  51556. if (!_this.isSupported) {
  51557. _this.dispose(camera);
  51558. }
  51559. _this.onActivate = null;
  51560. };
  51561. _this.onApplyObservable.add(function (effect) {
  51562. _this._updateMeshScreenCoordinates(scene);
  51563. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  51564. effect.setFloat("exposure", _this.exposure);
  51565. effect.setFloat("decay", _this.decay);
  51566. effect.setFloat("weight", _this.weight);
  51567. effect.setFloat("density", _this.density);
  51568. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  51569. });
  51570. return _this;
  51571. }
  51572. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  51573. get: function () {
  51574. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51575. return false;
  51576. },
  51577. set: function (useDiffuseColor) {
  51578. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  51579. },
  51580. enumerable: true,
  51581. configurable: true
  51582. });
  51583. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  51584. var mesh = subMesh.getMesh();
  51585. // Render this.mesh as default
  51586. if (mesh === this.mesh) {
  51587. return mesh.material.isReady(mesh);
  51588. }
  51589. var defines = [];
  51590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51591. var material = subMesh.getMaterial();
  51592. var needUV = false;
  51593. // Alpha test
  51594. if (material) {
  51595. if (material.needAlphaTesting()) {
  51596. defines.push("#define ALPHATEST");
  51597. }
  51598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51599. attribs.push(BABYLON.VertexBuffer.UVKind);
  51600. defines.push("#define UV1");
  51601. }
  51602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51603. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51604. defines.push("#define UV2");
  51605. }
  51606. }
  51607. // Bones
  51608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51611. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51612. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51613. }
  51614. else {
  51615. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51616. }
  51617. // Instances
  51618. if (useInstances) {
  51619. defines.push("#define INSTANCES");
  51620. attribs.push("world0");
  51621. attribs.push("world1");
  51622. attribs.push("world2");
  51623. attribs.push("world3");
  51624. }
  51625. // Get correct effect
  51626. var join = defines.join("\n");
  51627. if (this._cachedDefines !== join) {
  51628. this._cachedDefines = join;
  51629. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  51630. }
  51631. return this._volumetricLightScatteringPass.isReady();
  51632. };
  51633. /**
  51634. * Sets the new light position for light scattering effect
  51635. * @param {BABYLON.Vector3} The new custom light position
  51636. */
  51637. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  51638. this.customMeshPosition = position;
  51639. };
  51640. /**
  51641. * Returns the light position for light scattering effect
  51642. * @return {BABYLON.Vector3} The custom light position
  51643. */
  51644. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  51645. return this.customMeshPosition;
  51646. };
  51647. /**
  51648. * Disposes the internal assets and detaches the post-process from the camera
  51649. */
  51650. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  51651. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  51652. if (rttIndex !== -1) {
  51653. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  51654. }
  51655. this._volumetricLightScatteringRTT.dispose();
  51656. _super.prototype.dispose.call(this, camera);
  51657. };
  51658. /**
  51659. * Returns the render target texture used by the post-process
  51660. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  51661. */
  51662. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  51663. return this._volumetricLightScatteringRTT;
  51664. };
  51665. // Private methods
  51666. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  51667. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  51668. return true;
  51669. }
  51670. return false;
  51671. };
  51672. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  51673. var _this = this;
  51674. var engine = scene.getEngine();
  51675. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  51676. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51677. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51678. this._volumetricLightScatteringRTT.renderList = null;
  51679. this._volumetricLightScatteringRTT.renderParticles = false;
  51680. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  51681. // Custom render function for submeshes
  51682. var renderSubMesh = function (subMesh) {
  51683. var mesh = subMesh.getRenderingMesh();
  51684. if (_this._meshExcluded(mesh)) {
  51685. return;
  51686. }
  51687. var scene = mesh.getScene();
  51688. var engine = scene.getEngine();
  51689. // Culling
  51690. engine.setState(subMesh.getMaterial().backFaceCulling);
  51691. // Managing instances
  51692. var batch = mesh._getInstancesRenderList(subMesh._id);
  51693. if (batch.mustReturn) {
  51694. return;
  51695. }
  51696. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  51697. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  51698. var effect = _this._volumetricLightScatteringPass;
  51699. if (mesh === _this.mesh) {
  51700. effect = subMesh.getMaterial().getEffect();
  51701. }
  51702. engine.enableEffect(effect);
  51703. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  51704. if (mesh === _this.mesh) {
  51705. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  51706. }
  51707. else {
  51708. var material = subMesh.getMaterial();
  51709. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  51710. // Alpha test
  51711. if (material && material.needAlphaTesting()) {
  51712. var alphaTexture = material.getAlphaTestTexture();
  51713. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  51714. if (alphaTexture) {
  51715. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  51716. }
  51717. }
  51718. // Bones
  51719. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51720. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  51721. }
  51722. }
  51723. // Draw
  51724. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  51725. }
  51726. };
  51727. // Render target texture callbacks
  51728. var savedSceneClearColor;
  51729. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  51730. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  51731. savedSceneClearColor = scene.clearColor;
  51732. scene.clearColor = sceneClearColor;
  51733. });
  51734. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  51735. scene.clearColor = savedSceneClearColor;
  51736. });
  51737. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  51738. var engine = scene.getEngine();
  51739. var index;
  51740. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51741. renderSubMesh(opaqueSubMeshes.data[index]);
  51742. }
  51743. engine.setAlphaTesting(true);
  51744. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51745. renderSubMesh(alphaTestSubMeshes.data[index]);
  51746. }
  51747. engine.setAlphaTesting(false);
  51748. if (transparentSubMeshes.length) {
  51749. // Sort sub meshes
  51750. for (index = 0; index < transparentSubMeshes.length; index++) {
  51751. var submesh = transparentSubMeshes.data[index];
  51752. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  51753. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  51754. }
  51755. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  51756. sortedArray.sort(function (a, b) {
  51757. // Alpha index first
  51758. if (a._alphaIndex > b._alphaIndex) {
  51759. return 1;
  51760. }
  51761. if (a._alphaIndex < b._alphaIndex) {
  51762. return -1;
  51763. }
  51764. // Then distance to camera
  51765. if (a._distanceToCamera < b._distanceToCamera) {
  51766. return 1;
  51767. }
  51768. if (a._distanceToCamera > b._distanceToCamera) {
  51769. return -1;
  51770. }
  51771. return 0;
  51772. });
  51773. // Render sub meshes
  51774. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51775. for (index = 0; index < sortedArray.length; index++) {
  51776. renderSubMesh(sortedArray[index]);
  51777. }
  51778. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51779. }
  51780. };
  51781. };
  51782. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  51783. var transform = scene.getTransformMatrix();
  51784. var meshPosition;
  51785. if (this.useCustomMeshPosition) {
  51786. meshPosition = this.customMeshPosition;
  51787. }
  51788. else if (this.attachedNode) {
  51789. meshPosition = this.attachedNode.position;
  51790. }
  51791. else {
  51792. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  51793. }
  51794. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  51795. this._screenCoordinates.x = pos.x / this._viewPort.width;
  51796. this._screenCoordinates.y = pos.y / this._viewPort.height;
  51797. if (this.invert)
  51798. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  51799. };
  51800. // Static methods
  51801. /**
  51802. * Creates a default mesh for the Volumeric Light Scattering post-process
  51803. * @param {string} The mesh name
  51804. * @param {BABYLON.Scene} The scene where to create the mesh
  51805. * @return {BABYLON.Mesh} the default mesh
  51806. */
  51807. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  51808. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  51809. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  51810. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  51811. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  51812. mesh.material = material;
  51813. return mesh;
  51814. };
  51815. return VolumetricLightScatteringPostProcess;
  51816. }(BABYLON.PostProcess));
  51817. __decorate([
  51818. BABYLON.serializeAsVector3()
  51819. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  51820. __decorate([
  51821. BABYLON.serialize()
  51822. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  51823. __decorate([
  51824. BABYLON.serialize()
  51825. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  51826. __decorate([
  51827. BABYLON.serializeAsMeshReference()
  51828. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  51829. __decorate([
  51830. BABYLON.serialize()
  51831. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  51832. __decorate([
  51833. BABYLON.serialize()
  51834. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  51835. __decorate([
  51836. BABYLON.serialize()
  51837. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  51838. __decorate([
  51839. BABYLON.serialize()
  51840. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  51841. __decorate([
  51842. BABYLON.serialize()
  51843. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  51844. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  51845. })(BABYLON || (BABYLON = {}));
  51846. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  51847. // BABYLON.JS Chromatic Aberration GLSL Shader
  51848. // Author: Olivier Guyot
  51849. // Separates very slightly R, G and B colors on the edges of the screen
  51850. // Inspired by Francois Tarlier & Martins Upitis
  51851. var BABYLON;
  51852. (function (BABYLON) {
  51853. var LensRenderingPipeline = (function (_super) {
  51854. __extends(LensRenderingPipeline, _super);
  51855. /**
  51856. * @constructor
  51857. *
  51858. * Effect parameters are as follow:
  51859. * {
  51860. * chromatic_aberration: number; // from 0 to x (1 for realism)
  51861. * edge_blur: number; // from 0 to x (1 for realism)
  51862. * distortion: number; // from 0 to x (1 for realism)
  51863. * grain_amount: number; // from 0 to 1
  51864. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  51865. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  51866. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  51867. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  51868. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  51869. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  51870. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  51871. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  51872. * }
  51873. * Note: if an effect parameter is unset, effect is disabled
  51874. *
  51875. * @param {string} name - The rendering pipeline name
  51876. * @param {object} parameters - An object containing all parameters (see above)
  51877. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  51878. * @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)
  51879. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  51880. */
  51881. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  51882. if (ratio === void 0) { ratio = 1.0; }
  51883. var _this = _super.call(this, scene.getEngine(), name) || this;
  51884. // Lens effects can be of the following:
  51885. // - chromatic aberration (slight shift of RGB colors)
  51886. // - blur on the edge of the lens
  51887. // - lens distortion
  51888. // - depth-of-field blur & highlights enhancing
  51889. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  51890. // - grain effect (noise or custom texture)
  51891. // Two additional texture samplers are needed:
  51892. // - depth map (for depth-of-field)
  51893. // - grain texture
  51894. /**
  51895. * The chromatic aberration PostProcess id in the pipeline
  51896. * @type {string}
  51897. */
  51898. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  51899. /**
  51900. * The highlights enhancing PostProcess id in the pipeline
  51901. * @type {string}
  51902. */
  51903. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  51904. /**
  51905. * The depth-of-field PostProcess id in the pipeline
  51906. * @type {string}
  51907. */
  51908. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  51909. _this._scene = scene;
  51910. // Fetch texture samplers
  51911. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  51912. if (parameters.grain_texture) {
  51913. _this._grainTexture = parameters.grain_texture;
  51914. }
  51915. else {
  51916. _this._createGrainTexture();
  51917. }
  51918. // save parameters
  51919. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  51920. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  51921. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  51922. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  51923. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  51924. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  51925. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  51926. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  51927. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  51928. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  51929. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  51930. // Create effects
  51931. _this._createChromaticAberrationPostProcess(ratio);
  51932. _this._createHighlightsPostProcess(ratio);
  51933. _this._createDepthOfFieldPostProcess(ratio / 4);
  51934. // Set up pipeline
  51935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  51936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  51937. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  51938. if (_this._highlightsGain === -1) {
  51939. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  51940. }
  51941. // Finish
  51942. scene.postProcessRenderPipelineManager.addPipeline(_this);
  51943. if (cameras) {
  51944. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  51945. }
  51946. return _this;
  51947. }
  51948. // public methods (self explanatory)
  51949. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  51950. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  51951. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  51952. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  51953. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  51954. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  51955. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  51956. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  51957. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  51958. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  51959. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  51960. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  51961. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  51962. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  51963. };
  51964. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  51965. this._highlightsPostProcess.updateEffect();
  51966. };
  51967. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  51968. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  51969. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  51970. this._highlightsGain = amount;
  51971. };
  51972. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  51973. if (this._highlightsGain === -1) {
  51974. this._highlightsGain = 1.0;
  51975. }
  51976. this._highlightsThreshold = amount;
  51977. };
  51978. LensRenderingPipeline.prototype.disableHighlights = function () {
  51979. this._highlightsGain = -1;
  51980. };
  51981. /**
  51982. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  51983. */
  51984. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  51985. if (disableDepthRender === void 0) { disableDepthRender = false; }
  51986. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  51987. this._chromaticAberrationPostProcess = undefined;
  51988. this._highlightsPostProcess = undefined;
  51989. this._depthOfFieldPostProcess = undefined;
  51990. this._grainTexture.dispose();
  51991. if (disableDepthRender)
  51992. this._scene.disableDepthRenderer();
  51993. };
  51994. // colors shifting and distortion
  51995. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  51996. var _this = this;
  51997. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  51998. [], // samplers
  51999. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52000. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52001. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52002. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52003. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52004. };
  52005. };
  52006. // highlights enhancing
  52007. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52008. var _this = this;
  52009. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52010. [], // samplers
  52011. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52012. this._highlightsPostProcess.onApply = function (effect) {
  52013. effect.setFloat('gain', _this._highlightsGain);
  52014. effect.setFloat('threshold', _this._highlightsThreshold);
  52015. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52016. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52017. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52018. };
  52019. };
  52020. // colors shifting and distortion
  52021. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52022. var _this = this;
  52023. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52024. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52025. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52026. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52027. this._depthOfFieldPostProcess.onApply = function (effect) {
  52028. effect.setTexture("depthSampler", _this._depthTexture);
  52029. effect.setTexture("grainSampler", _this._grainTexture);
  52030. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52031. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52032. effect.setFloat('grain_amount', _this._grainAmount);
  52033. effect.setBool('blur_noise', _this._blurNoise);
  52034. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52035. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52036. effect.setFloat('distortion', _this._distortion);
  52037. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52038. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52039. effect.setFloat('aperture', _this._dofAperture);
  52040. effect.setFloat('darken', _this._dofDarken);
  52041. effect.setFloat('edge_blur', _this._edgeBlur);
  52042. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52043. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52044. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52045. };
  52046. };
  52047. // creates a black and white random noise texture, 512x512
  52048. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52049. var size = 512;
  52050. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52051. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52052. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52053. var context = this._grainTexture.getContext();
  52054. var rand = function (min, max) {
  52055. return Math.random() * (max - min) + min;
  52056. };
  52057. var value;
  52058. for (var x = 0; x < size; x++) {
  52059. for (var y = 0; y < size; y++) {
  52060. value = Math.floor(rand(0.42, 0.58) * 255);
  52061. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52062. context.fillRect(x, y, 1, 1);
  52063. }
  52064. }
  52065. this._grainTexture.update(false);
  52066. };
  52067. return LensRenderingPipeline;
  52068. }(BABYLON.PostProcessRenderPipeline));
  52069. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52070. })(BABYLON || (BABYLON = {}));
  52071. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52072. //
  52073. // This post-process allows the modification of rendered colors by using
  52074. // a 'look-up table' (LUT). This effect is also called Color Grading.
  52075. //
  52076. // The object needs to be provided an url to a texture containing the color
  52077. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  52078. // Use an image editing software to tweak the LUT to match your needs.
  52079. //
  52080. // For an example of a color LUT, see here:
  52081. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  52082. // For explanations on color grading, see here:
  52083. // http://udn.epicgames.com/Three/ColorGrading.html
  52084. //
  52085. var BABYLON;
  52086. (function (BABYLON) {
  52087. var ColorCorrectionPostProcess = (function (_super) {
  52088. __extends(ColorCorrectionPostProcess, _super);
  52089. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  52090. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  52091. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52092. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  52093. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52094. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52095. _this.onApply = function (effect) {
  52096. effect.setTexture("colorTable", _this._colorTableTexture);
  52097. };
  52098. return _this;
  52099. }
  52100. return ColorCorrectionPostProcess;
  52101. }(BABYLON.PostProcess));
  52102. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  52103. })(BABYLON || (BABYLON = {}));
  52104. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  52105. /// <reference path="babylon.freeCamera.ts" />
  52106. /// <reference path="babylon.arcRotateCamera.ts" />
  52107. /// <reference path="babylon.gamepadCamera.ts" />
  52108. /// <reference path="babylon.universalCamera.ts" />
  52109. var BABYLON;
  52110. (function (BABYLON) {
  52111. var AnaglyphFreeCamera = (function (_super) {
  52112. __extends(AnaglyphFreeCamera, _super);
  52113. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  52114. var _this = _super.call(this, name, position, scene) || this;
  52115. _this.interaxialDistance = interaxialDistance;
  52116. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52117. return _this;
  52118. }
  52119. AnaglyphFreeCamera.prototype.getClassName = function () {
  52120. return "AnaglyphFreeCamera";
  52121. };
  52122. return AnaglyphFreeCamera;
  52123. }(BABYLON.FreeCamera));
  52124. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  52125. var AnaglyphArcRotateCamera = (function (_super) {
  52126. __extends(AnaglyphArcRotateCamera, _super);
  52127. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  52128. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52129. _this.interaxialDistance = interaxialDistance;
  52130. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52131. return _this;
  52132. }
  52133. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  52134. return "AnaglyphArcRotateCamera";
  52135. };
  52136. return AnaglyphArcRotateCamera;
  52137. }(BABYLON.ArcRotateCamera));
  52138. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  52139. var AnaglyphGamepadCamera = (function (_super) {
  52140. __extends(AnaglyphGamepadCamera, _super);
  52141. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  52142. var _this = _super.call(this, name, position, scene) || this;
  52143. _this.interaxialDistance = interaxialDistance;
  52144. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52145. return _this;
  52146. }
  52147. AnaglyphGamepadCamera.prototype.getClassName = function () {
  52148. return "AnaglyphGamepadCamera";
  52149. };
  52150. return AnaglyphGamepadCamera;
  52151. }(BABYLON.GamepadCamera));
  52152. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  52153. var AnaglyphUniversalCamera = (function (_super) {
  52154. __extends(AnaglyphUniversalCamera, _super);
  52155. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  52156. var _this = _super.call(this, name, position, scene) || this;
  52157. _this.interaxialDistance = interaxialDistance;
  52158. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  52159. return _this;
  52160. }
  52161. AnaglyphUniversalCamera.prototype.getClassName = function () {
  52162. return "AnaglyphUniversalCamera";
  52163. };
  52164. return AnaglyphUniversalCamera;
  52165. }(BABYLON.UniversalCamera));
  52166. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  52167. var StereoscopicFreeCamera = (function (_super) {
  52168. __extends(StereoscopicFreeCamera, _super);
  52169. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52170. var _this = _super.call(this, name, position, scene) || this;
  52171. _this.interaxialDistance = interaxialDistance;
  52172. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52173. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52174. return _this;
  52175. }
  52176. StereoscopicFreeCamera.prototype.getClassName = function () {
  52177. return "StereoscopicFreeCamera";
  52178. };
  52179. return StereoscopicFreeCamera;
  52180. }(BABYLON.FreeCamera));
  52181. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  52182. var StereoscopicArcRotateCamera = (function (_super) {
  52183. __extends(StereoscopicArcRotateCamera, _super);
  52184. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  52185. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  52186. _this.interaxialDistance = interaxialDistance;
  52187. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52188. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52189. return _this;
  52190. }
  52191. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  52192. return "StereoscopicArcRotateCamera";
  52193. };
  52194. return StereoscopicArcRotateCamera;
  52195. }(BABYLON.ArcRotateCamera));
  52196. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  52197. var StereoscopicGamepadCamera = (function (_super) {
  52198. __extends(StereoscopicGamepadCamera, _super);
  52199. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52200. var _this = _super.call(this, name, position, scene) || this;
  52201. _this.interaxialDistance = interaxialDistance;
  52202. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52203. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52204. return _this;
  52205. }
  52206. StereoscopicGamepadCamera.prototype.getClassName = function () {
  52207. return "StereoscopicGamepadCamera";
  52208. };
  52209. return StereoscopicGamepadCamera;
  52210. }(BABYLON.GamepadCamera));
  52211. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  52212. var StereoscopicUniversalCamera = (function (_super) {
  52213. __extends(StereoscopicUniversalCamera, _super);
  52214. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  52215. var _this = _super.call(this, name, position, scene) || this;
  52216. _this.interaxialDistance = interaxialDistance;
  52217. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  52218. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  52219. return _this;
  52220. }
  52221. StereoscopicUniversalCamera.prototype.getClassName = function () {
  52222. return "StereoscopicUniversalCamera";
  52223. };
  52224. return StereoscopicUniversalCamera;
  52225. }(BABYLON.UniversalCamera));
  52226. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  52227. })(BABYLON || (BABYLON = {}));
  52228. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  52229. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  52230. var BABYLON;
  52231. (function (BABYLON) {
  52232. var HDRRenderingPipeline = (function (_super) {
  52233. __extends(HDRRenderingPipeline, _super);
  52234. /**
  52235. * @constructor
  52236. * @param {string} name - The rendering pipeline name
  52237. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52238. * @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)
  52239. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52240. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52241. */
  52242. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52243. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52244. var _this = _super.call(this, scene.getEngine(), name) || this;
  52245. /**
  52246. * Public members
  52247. */
  52248. // Gaussian Blur
  52249. /**
  52250. * Gaussian blur coefficient
  52251. * @type {number}
  52252. */
  52253. _this.gaussCoeff = 0.3;
  52254. /**
  52255. * Gaussian blur mean
  52256. * @type {number}
  52257. */
  52258. _this.gaussMean = 1.0;
  52259. /**
  52260. * Gaussian blur standard deviation
  52261. * @type {number}
  52262. */
  52263. _this.gaussStandDev = 0.8;
  52264. /**
  52265. * Gaussian blur multiplier. Multiplies the blur effect
  52266. * @type {number}
  52267. */
  52268. _this.gaussMultiplier = 4.0;
  52269. // HDR
  52270. /**
  52271. * Exposure, controls the overall intensity of the pipeline
  52272. * @type {number}
  52273. */
  52274. _this.exposure = 1.0;
  52275. /**
  52276. * Minimum luminance that the post-process can output. Luminance is >= 0
  52277. * @type {number}
  52278. */
  52279. _this.minimumLuminance = 1.0;
  52280. /**
  52281. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  52282. * @type {number}
  52283. */
  52284. _this.maximumLuminance = 1e20;
  52285. /**
  52286. * Increase rate for luminance: eye adaptation speed to dark
  52287. * @type {number}
  52288. */
  52289. _this.luminanceIncreaserate = 0.5;
  52290. /**
  52291. * Decrease rate for luminance: eye adaptation speed to bright
  52292. * @type {number}
  52293. */
  52294. _this.luminanceDecreaseRate = 0.5;
  52295. // Bright pass
  52296. /**
  52297. * Minimum luminance needed to compute HDR
  52298. * @type {number}
  52299. */
  52300. _this.brightThreshold = 0.8;
  52301. _this._needUpdate = true;
  52302. _this._scene = scene;
  52303. // Bright pass
  52304. _this._createBrightPassPostProcess(scene, ratio);
  52305. // Down sample X4
  52306. _this._createDownSampleX4PostProcess(scene, ratio);
  52307. // Create gaussian blur post-processes
  52308. _this._createGaussianBlurPostProcess(scene, ratio);
  52309. // Texture adder
  52310. _this._createTextureAdderPostProcess(scene, ratio);
  52311. // Luminance generator
  52312. _this._createLuminanceGeneratorPostProcess(scene);
  52313. // HDR
  52314. _this._createHDRPostProcess(scene, ratio);
  52315. // Pass postprocess
  52316. if (originalPostProcess === null) {
  52317. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52318. }
  52319. else {
  52320. _this._originalPostProcess = originalPostProcess;
  52321. }
  52322. // Configure pipeline
  52323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  52324. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  52325. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  52326. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  52327. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  52328. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  52329. var addDownSamplerPostProcess = function (id) {
  52330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  52331. };
  52332. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  52333. addDownSamplerPostProcess(i);
  52334. }
  52335. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  52336. // Finish
  52337. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52338. if (cameras !== null) {
  52339. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52340. }
  52341. _this.update();
  52342. return _this;
  52343. }
  52344. /**
  52345. * Tells the pipeline to update its post-processes
  52346. */
  52347. HDRRenderingPipeline.prototype.update = function () {
  52348. this._needUpdate = true;
  52349. };
  52350. /**
  52351. * Returns the current calculated luminance
  52352. */
  52353. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  52354. return this._hdrCurrentLuminance;
  52355. };
  52356. /**
  52357. * Returns the currently drawn luminance
  52358. */
  52359. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  52360. return this._hdrOutputLuminance;
  52361. };
  52362. /**
  52363. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  52364. */
  52365. HDRRenderingPipeline.prototype.dispose = function () {
  52366. for (var i = 0; i < this._scene.cameras.length; i++) {
  52367. var camera = this._scene.cameras[i];
  52368. this._originalPostProcess.dispose(camera);
  52369. this._brightPassPostProcess.dispose(camera);
  52370. this._downSampleX4PostProcess.dispose(camera);
  52371. this._guassianBlurHPostProcess.dispose(camera);
  52372. this._guassianBlurVPostProcess.dispose(camera);
  52373. this._textureAdderPostProcess.dispose(camera);
  52374. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  52375. this._downSamplePostProcesses[j].dispose(camera);
  52376. }
  52377. this._hdrPostProcess.dispose(camera);
  52378. }
  52379. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52380. _super.prototype.dispose.call(this);
  52381. };
  52382. /**
  52383. * Creates the HDR post-process and computes the luminance adaptation
  52384. */
  52385. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  52386. var _this = this;
  52387. var hdrLastLuminance = 0.0;
  52388. this._hdrOutputLuminance = -1.0;
  52389. this._hdrCurrentLuminance = 1.0;
  52390. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  52391. this._hdrPostProcess.onApply = function (effect) {
  52392. if (_this._hdrOutputLuminance < 0.0) {
  52393. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  52394. }
  52395. else {
  52396. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  52397. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  52398. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  52399. }
  52400. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  52401. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  52402. }
  52403. else {
  52404. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  52405. }
  52406. }
  52407. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  52408. hdrLastLuminance += scene.getEngine().getDeltaTime();
  52409. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  52410. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  52411. effect.setFloat("exposure", _this.exposure);
  52412. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  52413. _this._needUpdate = false;
  52414. };
  52415. };
  52416. /**
  52417. * Texture Adder post-process
  52418. */
  52419. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  52420. var _this = this;
  52421. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  52422. this._textureAdderPostProcess.onApply = function (effect) {
  52423. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  52424. };
  52425. };
  52426. /**
  52427. * Down sample X4 post-process
  52428. */
  52429. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  52430. var _this = this;
  52431. var downSampleX4Offsets = new Array(32);
  52432. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  52433. this._downSampleX4PostProcess.onApply = function (effect) {
  52434. if (_this._needUpdate) {
  52435. var id = 0;
  52436. for (var i = -2; i < 2; i++) {
  52437. for (var j = -2; j < 2; j++) {
  52438. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  52439. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  52440. id += 2;
  52441. }
  52442. }
  52443. }
  52444. effect.setArray2("dsOffsets", downSampleX4Offsets);
  52445. };
  52446. };
  52447. /**
  52448. * Bright pass post-process
  52449. */
  52450. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  52451. var _this = this;
  52452. var brightOffsets = new Array(8);
  52453. var brightPassCallback = function (effect) {
  52454. if (_this._needUpdate) {
  52455. var sU = (1.0 / _this._brightPassPostProcess.width);
  52456. var sV = (1.0 / _this._brightPassPostProcess.height);
  52457. brightOffsets[0] = -0.5 * sU;
  52458. brightOffsets[1] = 0.5 * sV;
  52459. brightOffsets[2] = 0.5 * sU;
  52460. brightOffsets[3] = 0.5 * sV;
  52461. brightOffsets[4] = -0.5 * sU;
  52462. brightOffsets[5] = -0.5 * sV;
  52463. brightOffsets[6] = 0.5 * sU;
  52464. brightOffsets[7] = -0.5 * sV;
  52465. }
  52466. effect.setArray2("dsOffsets", brightOffsets);
  52467. effect.setFloat("brightThreshold", _this.brightThreshold);
  52468. };
  52469. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  52470. this._brightPassPostProcess.onApply = brightPassCallback;
  52471. };
  52472. /**
  52473. * Luminance generator. Creates the luminance post-process and down sample post-processes
  52474. */
  52475. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  52476. var _this = this;
  52477. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  52478. var luminanceOffsets = new Array(8);
  52479. var downSampleOffsets = new Array(18);
  52480. var halfDestPixelSize;
  52481. this._downSamplePostProcesses = new Array(lumSteps);
  52482. // Utils for luminance
  52483. var luminanceUpdateSourceOffsets = function (width, height) {
  52484. var sU = (1.0 / width);
  52485. var sV = (1.0 / height);
  52486. luminanceOffsets[0] = -0.5 * sU;
  52487. luminanceOffsets[1] = 0.5 * sV;
  52488. luminanceOffsets[2] = 0.5 * sU;
  52489. luminanceOffsets[3] = 0.5 * sV;
  52490. luminanceOffsets[4] = -0.5 * sU;
  52491. luminanceOffsets[5] = -0.5 * sV;
  52492. luminanceOffsets[6] = 0.5 * sU;
  52493. luminanceOffsets[7] = -0.5 * sV;
  52494. };
  52495. var luminanceUpdateDestOffsets = function (width, height) {
  52496. var id = 0;
  52497. for (var x = -1; x < 2; x++) {
  52498. for (var y = -1; y < 2; y++) {
  52499. downSampleOffsets[id] = (x) / width;
  52500. downSampleOffsets[id + 1] = (y) / height;
  52501. id += 2;
  52502. }
  52503. }
  52504. };
  52505. // Luminance callback
  52506. var luminanceCallback = function (effect) {
  52507. if (_this._needUpdate) {
  52508. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  52509. }
  52510. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  52511. effect.setArray2("lumOffsets", luminanceOffsets);
  52512. };
  52513. // Down sample callbacks
  52514. var downSampleCallback = function (indice) {
  52515. var i = indice;
  52516. return function (effect) {
  52517. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  52518. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  52519. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  52520. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  52521. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  52522. effect.setArray2("dsOffsets", downSampleOffsets);
  52523. };
  52524. };
  52525. var downSampleAfterRenderCallback = function (effect) {
  52526. // Unpack result
  52527. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  52528. 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);
  52529. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  52530. };
  52531. // Create luminance post-process
  52532. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  52533. 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);
  52534. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  52535. // Create down sample post-processes
  52536. for (var i = lumSteps - 2; i >= 0; i--) {
  52537. var length = Math.pow(3, i);
  52538. ratio = { width: length, height: length };
  52539. var defines = "#define DOWN_SAMPLE\n";
  52540. if (i === 0) {
  52541. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  52542. }
  52543. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52544. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  52545. if (i === 0) {
  52546. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  52547. }
  52548. }
  52549. };
  52550. /**
  52551. * Gaussian blur post-processes. Horizontal and Vertical
  52552. */
  52553. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  52554. var _this = this;
  52555. var blurOffsetsW = new Array(9);
  52556. var blurOffsetsH = new Array(9);
  52557. var blurWeights = new Array(9);
  52558. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  52559. // Utils for gaussian blur
  52560. var calculateBlurOffsets = function (height) {
  52561. var lastOutputDimensions = {
  52562. width: scene.getEngine().getRenderWidth(),
  52563. height: scene.getEngine().getRenderHeight()
  52564. };
  52565. for (var i = 0; i < 9; i++) {
  52566. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  52567. if (height) {
  52568. blurOffsetsH[i] = value;
  52569. }
  52570. else {
  52571. blurOffsetsW[i] = value;
  52572. }
  52573. }
  52574. };
  52575. var calculateWeights = function () {
  52576. var x = 0.0;
  52577. for (var i = 0; i < 9; i++) {
  52578. x = (i - 4.0) / 4.0;
  52579. 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));
  52580. }
  52581. };
  52582. // Callback
  52583. var gaussianBlurCallback = function (height) {
  52584. return function (effect) {
  52585. if (_this._needUpdate) {
  52586. calculateWeights();
  52587. calculateBlurOffsets(height);
  52588. }
  52589. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  52590. effect.setArray("blurWeights", blurWeights);
  52591. effect.setFloat("multiplier", _this.gaussMultiplier);
  52592. };
  52593. };
  52594. // Create horizontal gaussian blur post-processes
  52595. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  52596. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  52597. // Create vertical gaussian blur post-process
  52598. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  52599. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  52600. };
  52601. return HDRRenderingPipeline;
  52602. }(BABYLON.PostProcessRenderPipeline));
  52603. // Luminance generator
  52604. HDRRenderingPipeline.LUM_STEPS = 6;
  52605. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  52606. })(BABYLON || (BABYLON = {}));
  52607. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  52608. var BABYLON;
  52609. (function (BABYLON) {
  52610. var FaceAdjacencies = (function () {
  52611. function FaceAdjacencies() {
  52612. this.edges = new Array();
  52613. this.edgesConnectedCount = 0;
  52614. }
  52615. return FaceAdjacencies;
  52616. }());
  52617. var EdgesRenderer = (function () {
  52618. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  52619. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  52620. if (epsilon === void 0) { epsilon = 0.95; }
  52621. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  52622. this.edgesWidthScalerForOrthographic = 1000.0;
  52623. this.edgesWidthScalerForPerspective = 50.0;
  52624. this._linesPositions = new Array();
  52625. this._linesNormals = new Array();
  52626. this._linesIndices = new Array();
  52627. this._buffers = {};
  52628. this._checkVerticesInsteadOfIndices = false;
  52629. this._source = source;
  52630. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  52631. this._epsilon = epsilon;
  52632. this._prepareRessources();
  52633. this._generateEdgesLines();
  52634. }
  52635. EdgesRenderer.prototype._prepareRessources = function () {
  52636. if (this._lineShader) {
  52637. return;
  52638. }
  52639. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  52640. attributes: ["position", "normal"],
  52641. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  52642. });
  52643. this._lineShader.disableDepthWrite = true;
  52644. this._lineShader.backFaceCulling = false;
  52645. };
  52646. EdgesRenderer.prototype.dispose = function () {
  52647. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  52648. if (buffer) {
  52649. buffer.dispose();
  52650. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  52651. }
  52652. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  52653. if (buffer) {
  52654. buffer.dispose();
  52655. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  52656. }
  52657. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  52658. this._lineShader.dispose();
  52659. };
  52660. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  52661. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  52662. return 0;
  52663. }
  52664. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  52665. return 1;
  52666. }
  52667. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  52668. return 2;
  52669. }
  52670. return -1;
  52671. };
  52672. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  52673. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  52674. return 0;
  52675. }
  52676. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  52677. return 1;
  52678. }
  52679. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  52680. return 2;
  52681. }
  52682. return -1;
  52683. };
  52684. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  52685. var needToCreateLine;
  52686. if (edge === undefined) {
  52687. needToCreateLine = true;
  52688. }
  52689. else {
  52690. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  52691. needToCreateLine = dotProduct < this._epsilon;
  52692. }
  52693. if (needToCreateLine) {
  52694. var offset = this._linesPositions.length / 3;
  52695. var normal = p0.subtract(p1);
  52696. normal.normalize();
  52697. // Positions
  52698. this._linesPositions.push(p0.x);
  52699. this._linesPositions.push(p0.y);
  52700. this._linesPositions.push(p0.z);
  52701. this._linesPositions.push(p0.x);
  52702. this._linesPositions.push(p0.y);
  52703. this._linesPositions.push(p0.z);
  52704. this._linesPositions.push(p1.x);
  52705. this._linesPositions.push(p1.y);
  52706. this._linesPositions.push(p1.z);
  52707. this._linesPositions.push(p1.x);
  52708. this._linesPositions.push(p1.y);
  52709. this._linesPositions.push(p1.z);
  52710. // Normals
  52711. this._linesNormals.push(p1.x);
  52712. this._linesNormals.push(p1.y);
  52713. this._linesNormals.push(p1.z);
  52714. this._linesNormals.push(-1);
  52715. this._linesNormals.push(p1.x);
  52716. this._linesNormals.push(p1.y);
  52717. this._linesNormals.push(p1.z);
  52718. this._linesNormals.push(1);
  52719. this._linesNormals.push(p0.x);
  52720. this._linesNormals.push(p0.y);
  52721. this._linesNormals.push(p0.z);
  52722. this._linesNormals.push(-1);
  52723. this._linesNormals.push(p0.x);
  52724. this._linesNormals.push(p0.y);
  52725. this._linesNormals.push(p0.z);
  52726. this._linesNormals.push(1);
  52727. // Indices
  52728. this._linesIndices.push(offset);
  52729. this._linesIndices.push(offset + 1);
  52730. this._linesIndices.push(offset + 2);
  52731. this._linesIndices.push(offset);
  52732. this._linesIndices.push(offset + 2);
  52733. this._linesIndices.push(offset + 3);
  52734. }
  52735. };
  52736. EdgesRenderer.prototype._generateEdgesLines = function () {
  52737. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52738. var indices = this._source.getIndices();
  52739. // First let's find adjacencies
  52740. var adjacencies = new Array();
  52741. var faceNormals = new Array();
  52742. var index;
  52743. var faceAdjacencies;
  52744. // Prepare faces
  52745. for (index = 0; index < indices.length; index += 3) {
  52746. faceAdjacencies = new FaceAdjacencies();
  52747. var p0Index = indices[index];
  52748. var p1Index = indices[index + 1];
  52749. var p2Index = indices[index + 2];
  52750. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  52751. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  52752. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  52753. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  52754. faceNormal.normalize();
  52755. faceNormals.push(faceNormal);
  52756. adjacencies.push(faceAdjacencies);
  52757. }
  52758. // Scan
  52759. for (index = 0; index < adjacencies.length; index++) {
  52760. faceAdjacencies = adjacencies[index];
  52761. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  52762. var otherFaceAdjacencies = adjacencies[otherIndex];
  52763. if (faceAdjacencies.edgesConnectedCount === 3) {
  52764. break;
  52765. }
  52766. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  52767. continue;
  52768. }
  52769. var otherP0 = indices[otherIndex * 3];
  52770. var otherP1 = indices[otherIndex * 3 + 1];
  52771. var otherP2 = indices[otherIndex * 3 + 2];
  52772. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  52773. var otherEdgeIndex;
  52774. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  52775. continue;
  52776. }
  52777. switch (edgeIndex) {
  52778. case 0:
  52779. if (this._checkVerticesInsteadOfIndices) {
  52780. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  52781. }
  52782. else {
  52783. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  52784. }
  52785. break;
  52786. case 1:
  52787. if (this._checkVerticesInsteadOfIndices) {
  52788. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  52789. }
  52790. else {
  52791. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  52792. }
  52793. break;
  52794. case 2:
  52795. if (this._checkVerticesInsteadOfIndices) {
  52796. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  52797. }
  52798. else {
  52799. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  52800. }
  52801. break;
  52802. }
  52803. if (otherEdgeIndex === -1) {
  52804. continue;
  52805. }
  52806. faceAdjacencies.edges[edgeIndex] = otherIndex;
  52807. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  52808. faceAdjacencies.edgesConnectedCount++;
  52809. otherFaceAdjacencies.edgesConnectedCount++;
  52810. if (faceAdjacencies.edgesConnectedCount === 3) {
  52811. break;
  52812. }
  52813. }
  52814. }
  52815. }
  52816. // Create lines
  52817. for (index = 0; index < adjacencies.length; index++) {
  52818. // 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
  52819. var current = adjacencies[index];
  52820. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  52821. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  52822. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  52823. }
  52824. // Merge into a single mesh
  52825. var engine = this._source.getScene().getEngine();
  52826. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  52827. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  52828. this._ib = engine.createIndexBuffer(this._linesIndices);
  52829. this._indicesCount = this._linesIndices.length;
  52830. };
  52831. EdgesRenderer.prototype.render = function () {
  52832. if (!this._lineShader.isReady()) {
  52833. return;
  52834. }
  52835. var scene = this._source.getScene();
  52836. var engine = scene.getEngine();
  52837. this._lineShader._preBind();
  52838. // VBOs
  52839. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  52840. scene.resetCachedMaterial();
  52841. this._lineShader.setColor4("color", this._source.edgesColor);
  52842. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  52843. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  52844. }
  52845. else {
  52846. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  52847. }
  52848. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  52849. this._lineShader.bind(this._source.getWorldMatrix());
  52850. // Draw order
  52851. engine.draw(true, 0, this._indicesCount);
  52852. this._lineShader.unbind();
  52853. engine.setDepthWrite(true);
  52854. };
  52855. return EdgesRenderer;
  52856. }());
  52857. BABYLON.EdgesRenderer = EdgesRenderer;
  52858. })(BABYLON || (BABYLON = {}));
  52859. //# sourceMappingURL=babylon.edgesRenderer.js.map
  52860. var BABYLON;
  52861. (function (BABYLON) {
  52862. var TonemappingOperator;
  52863. (function (TonemappingOperator) {
  52864. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  52865. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  52866. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  52867. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  52868. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  52869. ;
  52870. var TonemapPostProcess = (function (_super) {
  52871. __extends(TonemapPostProcess, _super);
  52872. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  52873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52874. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52875. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  52876. _this._operator = _operator;
  52877. _this.exposureAdjustment = exposureAdjustment;
  52878. var defines = "#define ";
  52879. if (_this._operator === TonemappingOperator.Hable)
  52880. defines += "HABLE_TONEMAPPING";
  52881. else if (_this._operator === TonemappingOperator.Reinhard)
  52882. defines += "REINHARD_TONEMAPPING";
  52883. else if (_this._operator === TonemappingOperator.HejiDawson)
  52884. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  52885. else if (_this._operator === TonemappingOperator.Photographic)
  52886. defines += "PHOTOGRAPHIC_TONEMAPPING";
  52887. //sadly a second call to create the effect.
  52888. _this.updateEffect(defines);
  52889. _this.onApply = function (effect) {
  52890. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  52891. };
  52892. return _this;
  52893. }
  52894. return TonemapPostProcess;
  52895. }(BABYLON.PostProcess));
  52896. BABYLON.TonemapPostProcess = TonemapPostProcess;
  52897. })(BABYLON || (BABYLON = {}));
  52898. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  52899. var BABYLON;
  52900. (function (BABYLON) {
  52901. var ReflectionProbe = (function () {
  52902. function ReflectionProbe(name, size, scene, generateMipMaps) {
  52903. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52904. var _this = this;
  52905. this.name = name;
  52906. this._viewMatrix = BABYLON.Matrix.Identity();
  52907. this._target = BABYLON.Vector3.Zero();
  52908. this._add = BABYLON.Vector3.Zero();
  52909. this.invertYAxis = false;
  52910. this.position = BABYLON.Vector3.Zero();
  52911. this._scene = scene;
  52912. this._scene.reflectionProbes.push(this);
  52913. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  52914. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  52915. switch (faceIndex) {
  52916. case 0:
  52917. _this._add.copyFromFloats(1, 0, 0);
  52918. break;
  52919. case 1:
  52920. _this._add.copyFromFloats(-1, 0, 0);
  52921. break;
  52922. case 2:
  52923. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  52924. break;
  52925. case 3:
  52926. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  52927. break;
  52928. case 4:
  52929. _this._add.copyFromFloats(0, 0, 1);
  52930. break;
  52931. case 5:
  52932. _this._add.copyFromFloats(0, 0, -1);
  52933. break;
  52934. }
  52935. if (_this._attachedMesh) {
  52936. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  52937. }
  52938. _this.position.addToRef(_this._add, _this._target);
  52939. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  52940. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  52941. });
  52942. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  52943. scene.updateTransformMatrix(true);
  52944. });
  52945. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  52946. }
  52947. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  52948. get: function () {
  52949. return this._renderTargetTexture.samples;
  52950. },
  52951. set: function (value) {
  52952. this._renderTargetTexture.samples = value;
  52953. },
  52954. enumerable: true,
  52955. configurable: true
  52956. });
  52957. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  52958. get: function () {
  52959. return this._renderTargetTexture.refreshRate;
  52960. },
  52961. set: function (value) {
  52962. this._renderTargetTexture.refreshRate = value;
  52963. },
  52964. enumerable: true,
  52965. configurable: true
  52966. });
  52967. ReflectionProbe.prototype.getScene = function () {
  52968. return this._scene;
  52969. };
  52970. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  52971. get: function () {
  52972. return this._renderTargetTexture;
  52973. },
  52974. enumerable: true,
  52975. configurable: true
  52976. });
  52977. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  52978. get: function () {
  52979. return this._renderTargetTexture.renderList;
  52980. },
  52981. enumerable: true,
  52982. configurable: true
  52983. });
  52984. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  52985. this._attachedMesh = mesh;
  52986. };
  52987. ReflectionProbe.prototype.dispose = function () {
  52988. var index = this._scene.reflectionProbes.indexOf(this);
  52989. if (index !== -1) {
  52990. // Remove from the scene if found
  52991. this._scene.reflectionProbes.splice(index, 1);
  52992. }
  52993. if (this._renderTargetTexture) {
  52994. this._renderTargetTexture.dispose();
  52995. this._renderTargetTexture = null;
  52996. }
  52997. };
  52998. return ReflectionProbe;
  52999. }());
  53000. BABYLON.ReflectionProbe = ReflectionProbe;
  53001. })(BABYLON || (BABYLON = {}));
  53002. //# sourceMappingURL=babylon.reflectionProbe.js.map
  53003. var BABYLON;
  53004. (function (BABYLON) {
  53005. var SolidParticle = (function () {
  53006. /**
  53007. * Creates a Solid Particle object.
  53008. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53009. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53010. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53011. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  53012. * `shapeId` (integer) is the model shape identifier in the SPS.
  53013. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53014. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  53015. */
  53016. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53017. this.idx = 0; // particle global index
  53018. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  53019. this.position = BABYLON.Vector3.Zero(); // position
  53020. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53021. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  53022. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  53023. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53024. this.alive = true; // alive
  53025. this.isVisible = true; // visibility
  53026. this._pos = 0; // index of this particle in the global "positions" array
  53027. this.shapeId = 0; // model shape id
  53028. this.idxInShape = 0; // index of the particle in its shape id
  53029. this.idx = particleIndex;
  53030. this._pos = positionIndex;
  53031. this._model = model;
  53032. this.shapeId = shapeId;
  53033. this.idxInShape = idxInShape;
  53034. this._sps = sps;
  53035. if (modelBoundingInfo) {
  53036. this._modelBoundingInfo = modelBoundingInfo;
  53037. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53038. }
  53039. }
  53040. Object.defineProperty(SolidParticle.prototype, "scale", {
  53041. /**
  53042. * legacy support, changed scale to scaling
  53043. */
  53044. get: function () {
  53045. return this.scaling;
  53046. },
  53047. set: function (scale) {
  53048. this.scaling = scale;
  53049. },
  53050. enumerable: true,
  53051. configurable: true
  53052. });
  53053. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53054. /**
  53055. * legacy support, changed quaternion to rotationQuaternion
  53056. */
  53057. get: function () {
  53058. return this.rotationQuaternion;
  53059. },
  53060. set: function (q) {
  53061. this.rotationQuaternion = q;
  53062. },
  53063. enumerable: true,
  53064. configurable: true
  53065. });
  53066. /**
  53067. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53068. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53069. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  53070. */
  53071. SolidParticle.prototype.intersectsMesh = function (target) {
  53072. if (!this._boundingInfo || !target._boundingInfo) {
  53073. return false;
  53074. }
  53075. if (this._sps._bSphereOnly) {
  53076. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53077. }
  53078. return this._boundingInfo.intersects(target._boundingInfo, false);
  53079. };
  53080. return SolidParticle;
  53081. }());
  53082. BABYLON.SolidParticle = SolidParticle;
  53083. var ModelShape = (function () {
  53084. /**
  53085. * 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.
  53086. * SPS internal tool, don't use it manually.
  53087. */
  53088. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  53089. this.shapeID = id;
  53090. this._shape = shape;
  53091. this._shapeUV = shapeUV;
  53092. this._positionFunction = posFunction;
  53093. this._vertexFunction = vtxFunction;
  53094. }
  53095. return ModelShape;
  53096. }());
  53097. BABYLON.ModelShape = ModelShape;
  53098. })(BABYLON || (BABYLON = {}));
  53099. //# sourceMappingURL=babylon.solidParticle.js.map
  53100. var BABYLON;
  53101. (function (BABYLON) {
  53102. /**
  53103. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53104. */
  53105. var SolidParticleSystem = (function () {
  53106. /**
  53107. * Creates a SPS (Solid Particle System) object.
  53108. * `name` (String) is the SPS name, this will be the underlying mesh name.
  53109. * `scene` (Scene) is the scene in which the SPS is added.
  53110. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  53111. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  53112. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  53113. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53114. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53115. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53116. */
  53117. function SolidParticleSystem(name, scene, options) {
  53118. // public members
  53119. /**
  53120. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53121. * Example : var p = SPS.particles[i];
  53122. */
  53123. this.particles = new Array();
  53124. /**
  53125. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53126. */
  53127. this.nbParticles = 0;
  53128. /**
  53129. * If the particles must ever face the camera (default false). Useful for planar particles.
  53130. */
  53131. this.billboard = false;
  53132. /**
  53133. * Recompute normals when adding a shape
  53134. */
  53135. this.recomputeNormals = true;
  53136. /**
  53137. * This a counter ofr your own usage. It's not set by any SPS functions.
  53138. */
  53139. this.counter = 0;
  53140. /**
  53141. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53142. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53143. */
  53144. this.vars = {};
  53145. this._positions = new Array();
  53146. this._indices = new Array();
  53147. this._normals = new Array();
  53148. this._colors = new Array();
  53149. this._uvs = new Array();
  53150. this._index = 0; // indices index
  53151. this._updatable = true;
  53152. this._pickable = false;
  53153. this._isVisibilityBoxLocked = false;
  53154. this._alwaysVisible = false;
  53155. this._shapeCounter = 0;
  53156. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  53157. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53158. this._computeParticleColor = true;
  53159. this._computeParticleTexture = true;
  53160. this._computeParticleRotation = true;
  53161. this._computeParticleVertex = false;
  53162. this._computeBoundingBox = false;
  53163. this._cam_axisZ = BABYLON.Vector3.Zero();
  53164. this._cam_axisY = BABYLON.Vector3.Zero();
  53165. this._cam_axisX = BABYLON.Vector3.Zero();
  53166. this._axisX = BABYLON.Axis.X;
  53167. this._axisY = BABYLON.Axis.Y;
  53168. this._axisZ = BABYLON.Axis.Z;
  53169. this._camDir = BABYLON.Vector3.Zero();
  53170. this._rotMatrix = new BABYLON.Matrix();
  53171. this._invertMatrix = new BABYLON.Matrix();
  53172. this._rotated = BABYLON.Vector3.Zero();
  53173. this._quaternion = new BABYLON.Quaternion();
  53174. this._vertex = BABYLON.Vector3.Zero();
  53175. this._normal = BABYLON.Vector3.Zero();
  53176. this._yaw = 0.0;
  53177. this._pitch = 0.0;
  53178. this._roll = 0.0;
  53179. this._halfroll = 0.0;
  53180. this._halfpitch = 0.0;
  53181. this._halfyaw = 0.0;
  53182. this._sinRoll = 0.0;
  53183. this._cosRoll = 0.0;
  53184. this._sinPitch = 0.0;
  53185. this._cosPitch = 0.0;
  53186. this._sinYaw = 0.0;
  53187. this._cosYaw = 0.0;
  53188. this._w = 0.0;
  53189. this._mustUnrotateFixedNormals = false;
  53190. this._minimum = BABYLON.Tmp.Vector3[0];
  53191. this._maximum = BABYLON.Tmp.Vector3[1];
  53192. this._scale = BABYLON.Tmp.Vector3[2];
  53193. this._translation = BABYLON.Tmp.Vector3[3];
  53194. this._minBbox = BABYLON.Tmp.Vector3[4];
  53195. this._maxBbox = BABYLON.Tmp.Vector3[5];
  53196. this._particlesIntersect = false;
  53197. this._bSphereOnly = false;
  53198. this._bSphereRadiusFactor = 1.0;
  53199. this.name = name;
  53200. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53201. this._camera = scene.activeCamera;
  53202. this._pickable = options ? options.isPickable : false;
  53203. this._particlesIntersect = options ? options.particleIntersection : false;
  53204. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53205. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53206. if (options && options.updatable) {
  53207. this._updatable = options.updatable;
  53208. }
  53209. else {
  53210. this._updatable = true;
  53211. }
  53212. if (this._pickable) {
  53213. this.pickedParticles = [];
  53214. }
  53215. }
  53216. /**
  53217. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53218. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53219. */
  53220. SolidParticleSystem.prototype.buildMesh = function () {
  53221. if (this.nbParticles === 0) {
  53222. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53223. this.addShape(triangle, 1);
  53224. triangle.dispose();
  53225. }
  53226. this._positions32 = new Float32Array(this._positions);
  53227. this._uvs32 = new Float32Array(this._uvs);
  53228. this._colors32 = new Float32Array(this._colors);
  53229. if (this.recomputeNormals) {
  53230. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  53231. }
  53232. this._normals32 = new Float32Array(this._normals);
  53233. this._fixedNormal32 = new Float32Array(this._normals);
  53234. if (this._mustUnrotateFixedNormals) {
  53235. this._unrotateFixedNormals();
  53236. }
  53237. var vertexData = new BABYLON.VertexData();
  53238. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53239. vertexData.indices = this._indices;
  53240. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53241. if (this._uvs32) {
  53242. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53243. ;
  53244. }
  53245. if (this._colors32) {
  53246. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53247. }
  53248. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53249. vertexData.applyToMesh(mesh, this._updatable);
  53250. this.mesh = mesh;
  53251. this.mesh.isPickable = this._pickable;
  53252. // free memory
  53253. this._positions = null;
  53254. this._normals = null;
  53255. this._uvs = null;
  53256. this._colors = null;
  53257. if (!this._updatable) {
  53258. this.particles.length = 0;
  53259. }
  53260. return mesh;
  53261. };
  53262. /**
  53263. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53264. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53265. * Thus the particles generated from `digest()` have their property `position` set yet.
  53266. * `mesh` ( Mesh ) is the mesh to be digested
  53267. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  53268. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53269. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53270. */
  53271. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53272. var size = (options && options.facetNb) || 1;
  53273. var number = (options && options.number);
  53274. var delta = (options && options.delta) || 0;
  53275. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53276. var meshInd = mesh.getIndices();
  53277. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53278. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53279. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53280. var f = 0; // facet counter
  53281. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53282. // compute size from number
  53283. if (number) {
  53284. number = (number > totalFacets) ? totalFacets : number;
  53285. size = Math.round(totalFacets / number);
  53286. delta = 0;
  53287. }
  53288. else {
  53289. size = (size > totalFacets) ? totalFacets : size;
  53290. }
  53291. var facetPos = []; // submesh positions
  53292. var facetInd = []; // submesh indices
  53293. var facetUV = []; // submesh UV
  53294. var facetCol = []; // submesh colors
  53295. var barycenter = BABYLON.Tmp.Vector3[0];
  53296. var rand;
  53297. var sizeO = size;
  53298. while (f < totalFacets) {
  53299. size = sizeO + Math.floor((1 + delta) * Math.random());
  53300. if (f > totalFacets - size) {
  53301. size = totalFacets - f;
  53302. }
  53303. // reset temp arrays
  53304. facetPos.length = 0;
  53305. facetInd.length = 0;
  53306. facetUV.length = 0;
  53307. facetCol.length = 0;
  53308. // iterate over "size" facets
  53309. var fi = 0;
  53310. for (var j = f * 3; j < (f + size) * 3; j++) {
  53311. facetInd.push(fi);
  53312. var i = meshInd[j];
  53313. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53314. if (meshUV) {
  53315. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53316. }
  53317. if (meshCol) {
  53318. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53319. }
  53320. fi++;
  53321. }
  53322. // create a model shape for each single particle
  53323. var idx = this.nbParticles;
  53324. var shape = this._posToShape(facetPos);
  53325. var shapeUV = this._uvsToShapeUV(facetUV);
  53326. // compute the barycenter of the shape
  53327. var v;
  53328. for (v = 0; v < shape.length; v++) {
  53329. barycenter.addInPlace(shape[v]);
  53330. }
  53331. barycenter.scaleInPlace(1 / shape.length);
  53332. // shift the shape from its barycenter to the origin
  53333. for (v = 0; v < shape.length; v++) {
  53334. shape[v].subtractInPlace(barycenter);
  53335. }
  53336. var bInfo;
  53337. if (this._particlesIntersect) {
  53338. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53339. }
  53340. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  53341. // add the particle in the SPS
  53342. var currentPos = this._positions.length;
  53343. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53344. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  53345. // initialize the particle position
  53346. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53347. this._index += shape.length;
  53348. idx++;
  53349. this.nbParticles++;
  53350. this._shapeCounter++;
  53351. f += size;
  53352. }
  53353. return this;
  53354. };
  53355. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53356. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53357. var index = 0;
  53358. var idx = 0;
  53359. for (var p = 0; p < this.particles.length; p++) {
  53360. this._particle = this.particles[p];
  53361. this._shape = this._particle._model._shape;
  53362. if (this._particle.rotationQuaternion) {
  53363. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53364. }
  53365. else {
  53366. this._yaw = this._particle.rotation.y;
  53367. this._pitch = this._particle.rotation.x;
  53368. this._roll = this._particle.rotation.z;
  53369. this._quaternionRotationYPR();
  53370. }
  53371. this._quaternionToRotationMatrix();
  53372. this._rotMatrix.invertToRef(this._invertMatrix);
  53373. for (var pt = 0; pt < this._shape.length; pt++) {
  53374. idx = index + pt * 3;
  53375. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53376. this._fixedNormal32[idx] = this._normal.x;
  53377. this._fixedNormal32[idx + 1] = this._normal.y;
  53378. this._fixedNormal32[idx + 2] = this._normal.z;
  53379. }
  53380. index = idx + 3;
  53381. }
  53382. };
  53383. //reset copy
  53384. SolidParticleSystem.prototype._resetCopy = function () {
  53385. this._copy.position.x = 0;
  53386. this._copy.position.y = 0;
  53387. this._copy.position.z = 0;
  53388. this._copy.rotation.x = 0;
  53389. this._copy.rotation.y = 0;
  53390. this._copy.rotation.z = 0;
  53391. this._copy.rotationQuaternion = null;
  53392. this._copy.scaling.x = 1;
  53393. this._copy.scaling.y = 1;
  53394. this._copy.scaling.z = 1;
  53395. this._copy.uvs.x = 0;
  53396. this._copy.uvs.y = 0;
  53397. this._copy.uvs.z = 1;
  53398. this._copy.uvs.w = 1;
  53399. this._copy.color = null;
  53400. };
  53401. // _meshBuilder : inserts the shape model in the global SPS mesh
  53402. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53403. var i;
  53404. var u = 0;
  53405. var c = 0;
  53406. var n = 0;
  53407. this._resetCopy();
  53408. if (options && options.positionFunction) {
  53409. options.positionFunction(this._copy, idx, idxInShape);
  53410. this._mustUnrotateFixedNormals = true;
  53411. }
  53412. if (this._copy.rotationQuaternion) {
  53413. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53414. }
  53415. else {
  53416. this._yaw = this._copy.rotation.y;
  53417. this._pitch = this._copy.rotation.x;
  53418. this._roll = this._copy.rotation.z;
  53419. this._quaternionRotationYPR();
  53420. }
  53421. this._quaternionToRotationMatrix();
  53422. for (i = 0; i < shape.length; i++) {
  53423. this._vertex.x = shape[i].x;
  53424. this._vertex.y = shape[i].y;
  53425. this._vertex.z = shape[i].z;
  53426. if (options && options.vertexFunction) {
  53427. options.vertexFunction(this._copy, this._vertex, i);
  53428. }
  53429. this._vertex.x *= this._copy.scaling.x;
  53430. this._vertex.y *= this._copy.scaling.y;
  53431. this._vertex.z *= this._copy.scaling.z;
  53432. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53433. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53434. if (meshUV) {
  53435. 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);
  53436. u += 2;
  53437. }
  53438. if (this._copy.color) {
  53439. this._color = this._copy.color;
  53440. }
  53441. else if (meshCol && meshCol[c] !== undefined) {
  53442. this._color.r = meshCol[c];
  53443. this._color.g = meshCol[c + 1];
  53444. this._color.b = meshCol[c + 2];
  53445. this._color.a = meshCol[c + 3];
  53446. }
  53447. else {
  53448. this._color.r = 1;
  53449. this._color.g = 1;
  53450. this._color.b = 1;
  53451. this._color.a = 1;
  53452. }
  53453. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53454. c += 4;
  53455. if (!this.recomputeNormals && meshNor) {
  53456. this._normal.x = meshNor[n];
  53457. this._normal.y = meshNor[n + 1];
  53458. this._normal.z = meshNor[n + 2];
  53459. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53460. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53461. n += 3;
  53462. }
  53463. }
  53464. for (i = 0; i < meshInd.length; i++) {
  53465. indices.push(p + meshInd[i]);
  53466. }
  53467. if (this._pickable) {
  53468. var nbfaces = meshInd.length / 3;
  53469. for (i = 0; i < nbfaces; i++) {
  53470. this.pickedParticles.push({ idx: idx, faceId: i });
  53471. }
  53472. }
  53473. return this._copy;
  53474. };
  53475. // returns a shape array from positions array
  53476. SolidParticleSystem.prototype._posToShape = function (positions) {
  53477. var shape = [];
  53478. for (var i = 0; i < positions.length; i += 3) {
  53479. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53480. }
  53481. return shape;
  53482. };
  53483. // returns a shapeUV array from a Vector4 uvs
  53484. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53485. var shapeUV = [];
  53486. if (uvs) {
  53487. for (var i = 0; i < uvs.length; i++)
  53488. shapeUV.push(uvs[i]);
  53489. }
  53490. return shapeUV;
  53491. };
  53492. // adds a new particle object in the particles array
  53493. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  53494. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  53495. this.particles.push(sp);
  53496. return sp;
  53497. };
  53498. /**
  53499. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53500. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53501. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  53502. * `nb` (positive integer) the number of particles to be created from this model
  53503. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  53504. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  53505. */
  53506. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53507. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53508. var meshInd = mesh.getIndices();
  53509. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53510. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53511. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53512. var bbInfo;
  53513. if (this._particlesIntersect) {
  53514. bbInfo = mesh.getBoundingInfo();
  53515. }
  53516. var shape = this._posToShape(meshPos);
  53517. var shapeUV = this._uvsToShapeUV(meshUV);
  53518. var posfunc = options ? options.positionFunction : null;
  53519. var vtxfunc = options ? options.vertexFunction : null;
  53520. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  53521. // particles
  53522. var sp;
  53523. var currentCopy;
  53524. var idx = this.nbParticles;
  53525. for (var i = 0; i < nb; i++) {
  53526. var currentPos = this._positions.length;
  53527. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53528. if (this._updatable) {
  53529. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  53530. sp.position.copyFrom(currentCopy.position);
  53531. sp.rotation.copyFrom(currentCopy.rotation);
  53532. if (currentCopy.rotationQuaternion) {
  53533. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53534. }
  53535. if (currentCopy.color) {
  53536. sp.color.copyFrom(currentCopy.color);
  53537. }
  53538. sp.scaling.copyFrom(currentCopy.scaling);
  53539. sp.uvs.copyFrom(currentCopy.uvs);
  53540. }
  53541. this._index += shape.length;
  53542. idx++;
  53543. }
  53544. this.nbParticles += nb;
  53545. this._shapeCounter++;
  53546. return this._shapeCounter - 1;
  53547. };
  53548. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53549. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53550. this._resetCopy();
  53551. if (particle._model._positionFunction) {
  53552. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53553. }
  53554. if (this._copy.rotationQuaternion) {
  53555. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53556. }
  53557. else {
  53558. this._yaw = this._copy.rotation.y;
  53559. this._pitch = this._copy.rotation.x;
  53560. this._roll = this._copy.rotation.z;
  53561. this._quaternionRotationYPR();
  53562. }
  53563. this._quaternionToRotationMatrix();
  53564. this._shape = particle._model._shape;
  53565. for (var pt = 0; pt < this._shape.length; pt++) {
  53566. this._vertex.x = this._shape[pt].x;
  53567. this._vertex.y = this._shape[pt].y;
  53568. this._vertex.z = this._shape[pt].z;
  53569. if (particle._model._vertexFunction) {
  53570. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53571. }
  53572. this._vertex.x *= this._copy.scaling.x;
  53573. this._vertex.y *= this._copy.scaling.y;
  53574. this._vertex.z *= this._copy.scaling.z;
  53575. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53576. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53577. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53578. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53579. }
  53580. particle.position.x = 0.0;
  53581. particle.position.y = 0.0;
  53582. particle.position.z = 0.0;
  53583. particle.rotation.x = 0.0;
  53584. particle.rotation.y = 0.0;
  53585. particle.rotation.z = 0.0;
  53586. particle.rotationQuaternion = null;
  53587. particle.scaling.x = 1.0;
  53588. particle.scaling.y = 1.0;
  53589. particle.scaling.z = 1.0;
  53590. };
  53591. /**
  53592. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53593. * Returns the SPS.
  53594. */
  53595. SolidParticleSystem.prototype.rebuildMesh = function () {
  53596. for (var p = 0; p < this.particles.length; p++) {
  53597. this._rebuildParticle(this.particles[p]);
  53598. }
  53599. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53600. return this;
  53601. };
  53602. /**
  53603. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53604. * This method calls `updateParticle()` for each particle of the SPS.
  53605. * For an animated SPS, it is usually called within the render loop.
  53606. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53607. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53608. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53609. * Returns the SPS.
  53610. */
  53611. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53612. if (start === void 0) { start = 0; }
  53613. if (end === void 0) { end = this.nbParticles - 1; }
  53614. if (update === void 0) { update = true; }
  53615. if (!this._updatable) {
  53616. return;
  53617. }
  53618. // custom beforeUpdate
  53619. this.beforeUpdateParticles(start, end, update);
  53620. this._cam_axisX.x = 1.0;
  53621. this._cam_axisX.y = 0.0;
  53622. this._cam_axisX.z = 0.0;
  53623. this._cam_axisY.x = 0.0;
  53624. this._cam_axisY.y = 1.0;
  53625. this._cam_axisY.z = 0.0;
  53626. this._cam_axisZ.x = 0.0;
  53627. this._cam_axisZ.y = 0.0;
  53628. this._cam_axisZ.z = 1.0;
  53629. // if the particles will always face the camera
  53630. if (this.billboard) {
  53631. this.mesh.computeWorldMatrix(true);
  53632. // compute the camera position and un-rotate it by the current mesh rotation
  53633. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  53634. this._quaternionToRotationMatrix();
  53635. this._rotMatrix.invertToRef(this._invertMatrix);
  53636. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  53637. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53638. this._cam_axisZ.normalize();
  53639. // same for camera up vector extracted from the cam view matrix
  53640. var view = this._camera.getViewMatrix(true);
  53641. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53642. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53643. this._cam_axisY.normalize();
  53644. this._cam_axisX.normalize();
  53645. }
  53646. }
  53647. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53648. var idx = 0; // current position index in the global array positions32
  53649. var index = 0; // position start index in the global array positions32 of the current particle
  53650. var colidx = 0; // current color index in the global array colors32
  53651. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53652. var uvidx = 0; // current uv index in the global array uvs32
  53653. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53654. var pt = 0; // current index in the particle model shape
  53655. if (this.mesh.isFacetDataEnabled) {
  53656. this._computeBoundingBox = true;
  53657. }
  53658. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53659. if (this._computeBoundingBox) {
  53660. if (start == 0 && end == this.nbParticles - 1) {
  53661. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53662. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53663. }
  53664. else {
  53665. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53666. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53667. }
  53668. }
  53669. // particle loop
  53670. index = this.particles[start]._pos;
  53671. var vpos = (index / 3) | 0;
  53672. colorIndex = vpos * 4;
  53673. uvIndex = vpos * 2;
  53674. for (var p = start; p <= end; p++) {
  53675. this._particle = this.particles[p];
  53676. this._shape = this._particle._model._shape;
  53677. this._shapeUV = this._particle._model._shapeUV;
  53678. // call to custom user function to update the particle properties
  53679. this.updateParticle(this._particle);
  53680. if (this._particle.isVisible) {
  53681. // particle rotation matrix
  53682. if (this.billboard) {
  53683. this._particle.rotation.x = 0.0;
  53684. this._particle.rotation.y = 0.0;
  53685. }
  53686. if (this._computeParticleRotation || this.billboard) {
  53687. if (this._particle.rotationQuaternion) {
  53688. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53689. }
  53690. else {
  53691. this._yaw = this._particle.rotation.y;
  53692. this._pitch = this._particle.rotation.x;
  53693. this._roll = this._particle.rotation.z;
  53694. this._quaternionRotationYPR();
  53695. }
  53696. this._quaternionToRotationMatrix();
  53697. }
  53698. // particle vertex loop
  53699. for (pt = 0; pt < this._shape.length; pt++) {
  53700. idx = index + pt * 3;
  53701. colidx = colorIndex + pt * 4;
  53702. uvidx = uvIndex + pt * 2;
  53703. this._vertex.x = this._shape[pt].x;
  53704. this._vertex.y = this._shape[pt].y;
  53705. this._vertex.z = this._shape[pt].z;
  53706. if (this._computeParticleVertex) {
  53707. this.updateParticleVertex(this._particle, this._vertex, pt);
  53708. }
  53709. // positions
  53710. this._vertex.x *= this._particle.scaling.x;
  53711. this._vertex.y *= this._particle.scaling.y;
  53712. this._vertex.z *= this._particle.scaling.z;
  53713. 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];
  53714. 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;
  53715. 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;
  53716. 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;
  53717. 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;
  53718. 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;
  53719. 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;
  53720. if (this._computeBoundingBox) {
  53721. if (this._positions32[idx] < this._minimum.x) {
  53722. this._minimum.x = this._positions32[idx];
  53723. }
  53724. if (this._positions32[idx] > this._maximum.x) {
  53725. this._maximum.x = this._positions32[idx];
  53726. }
  53727. if (this._positions32[idx + 1] < this._minimum.y) {
  53728. this._minimum.y = this._positions32[idx + 1];
  53729. }
  53730. if (this._positions32[idx + 1] > this._maximum.y) {
  53731. this._maximum.y = this._positions32[idx + 1];
  53732. }
  53733. if (this._positions32[idx + 2] < this._minimum.z) {
  53734. this._minimum.z = this._positions32[idx + 2];
  53735. }
  53736. if (this._positions32[idx + 2] > this._maximum.z) {
  53737. this._maximum.z = this._positions32[idx + 2];
  53738. }
  53739. }
  53740. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53741. if (!this._computeParticleVertex) {
  53742. this._normal.x = this._fixedNormal32[idx];
  53743. this._normal.y = this._fixedNormal32[idx + 1];
  53744. this._normal.z = this._fixedNormal32[idx + 2];
  53745. 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]);
  53746. 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]);
  53747. 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]);
  53748. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53749. 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;
  53750. 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;
  53751. }
  53752. if (this._computeParticleColor) {
  53753. this._colors32[colidx] = this._particle.color.r;
  53754. this._colors32[colidx + 1] = this._particle.color.g;
  53755. this._colors32[colidx + 2] = this._particle.color.b;
  53756. this._colors32[colidx + 3] = this._particle.color.a;
  53757. }
  53758. if (this._computeParticleTexture) {
  53759. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53760. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53761. }
  53762. }
  53763. }
  53764. else {
  53765. for (pt = 0; pt < this._shape.length; pt++) {
  53766. idx = index + pt * 3;
  53767. colidx = colorIndex + pt * 4;
  53768. uvidx = uvIndex + pt * 2;
  53769. this._positions32[idx] = this._camera.position.x;
  53770. this._positions32[idx + 1] = this._camera.position.y;
  53771. this._positions32[idx + 2] = this._camera.position.z;
  53772. this._normals32[idx] = 0.0;
  53773. this._normals32[idx + 1] = 0.0;
  53774. this._normals32[idx + 2] = 0.0;
  53775. if (this._computeParticleColor) {
  53776. this._colors32[colidx] = this._particle.color.r;
  53777. this._colors32[colidx + 1] = this._particle.color.g;
  53778. this._colors32[colidx + 2] = this._particle.color.b;
  53779. this._colors32[colidx + 3] = this._particle.color.a;
  53780. }
  53781. if (this._computeParticleTexture) {
  53782. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53783. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53784. }
  53785. }
  53786. }
  53787. // if the particle intersections must be computed : update the bbInfo
  53788. if (this._particlesIntersect) {
  53789. var bInfo = this._particle._boundingInfo;
  53790. var bBox = bInfo.boundingBox;
  53791. var bSphere = bInfo.boundingSphere;
  53792. if (!this._bSphereOnly) {
  53793. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53794. for (var b = 0; b < bBox.vectors.length; b++) {
  53795. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53796. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53797. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53798. 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];
  53799. 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;
  53800. 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;
  53801. 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;
  53802. 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;
  53803. 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;
  53804. 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;
  53805. }
  53806. bBox._update(this.mesh._worldMatrix);
  53807. }
  53808. // place and scale the particle bouding sphere in the SPS local system, then update it
  53809. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53810. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53811. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53812. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53813. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53814. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53815. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53816. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53817. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53818. 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));
  53819. bSphere._update(this.mesh._worldMatrix);
  53820. }
  53821. // increment indexes for the next particle
  53822. index = idx + 3;
  53823. colorIndex = colidx + 4;
  53824. uvIndex = uvidx + 2;
  53825. }
  53826. // if the VBO must be updated
  53827. if (update) {
  53828. if (this._computeParticleColor) {
  53829. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53830. }
  53831. if (this._computeParticleTexture) {
  53832. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53833. }
  53834. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53835. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53836. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53837. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53838. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53839. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  53840. for (var i = 0; i < this._normals32.length; i++) {
  53841. this._fixedNormal32[i] = this._normals32[i];
  53842. }
  53843. }
  53844. if (!this.mesh.areNormalsFrozen) {
  53845. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53846. }
  53847. }
  53848. }
  53849. if (this._computeBoundingBox) {
  53850. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53851. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53852. }
  53853. this.afterUpdateParticles(start, end, update);
  53854. return this;
  53855. };
  53856. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53857. this._halfroll = this._roll * 0.5;
  53858. this._halfpitch = this._pitch * 0.5;
  53859. this._halfyaw = this._yaw * 0.5;
  53860. this._sinRoll = Math.sin(this._halfroll);
  53861. this._cosRoll = Math.cos(this._halfroll);
  53862. this._sinPitch = Math.sin(this._halfpitch);
  53863. this._cosPitch = Math.cos(this._halfpitch);
  53864. this._sinYaw = Math.sin(this._halfyaw);
  53865. this._cosYaw = Math.cos(this._halfyaw);
  53866. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  53867. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  53868. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  53869. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  53870. };
  53871. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53872. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53873. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53874. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53875. this._rotMatrix.m[3] = 0;
  53876. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53877. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53878. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53879. this._rotMatrix.m[7] = 0;
  53880. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53881. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53882. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53883. this._rotMatrix.m[11] = 0;
  53884. this._rotMatrix.m[12] = 0;
  53885. this._rotMatrix.m[13] = 0;
  53886. this._rotMatrix.m[14] = 0;
  53887. this._rotMatrix.m[15] = 1.0;
  53888. };
  53889. /**
  53890. * Disposes the SPS.
  53891. * Returns nothing.
  53892. */
  53893. SolidParticleSystem.prototype.dispose = function () {
  53894. this.mesh.dispose();
  53895. this.vars = null;
  53896. // drop references to internal big arrays for the GC
  53897. this._positions = null;
  53898. this._indices = null;
  53899. this._normals = null;
  53900. this._uvs = null;
  53901. this._colors = null;
  53902. this._positions32 = null;
  53903. this._normals32 = null;
  53904. this._fixedNormal32 = null;
  53905. this._uvs32 = null;
  53906. this._colors32 = null;
  53907. this.pickedParticles = null;
  53908. };
  53909. /**
  53910. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53911. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53912. * Returns the SPS.
  53913. */
  53914. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53915. if (!this._isVisibilityBoxLocked) {
  53916. this.mesh.refreshBoundingInfo();
  53917. }
  53918. return this;
  53919. };
  53920. /**
  53921. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53922. * @param size the size (float) of the visibility box
  53923. * note : this doesn't lock the SPS mesh bounding box.
  53924. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53925. */
  53926. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53927. var vis = size / 2;
  53928. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53929. };
  53930. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53931. // getter and setter
  53932. get: function () {
  53933. return this._alwaysVisible;
  53934. },
  53935. /**
  53936. * Sets the SPS as always visible or not
  53937. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53938. */
  53939. set: function (val) {
  53940. this._alwaysVisible = val;
  53941. this.mesh.alwaysSelectAsActiveMesh = val;
  53942. },
  53943. enumerable: true,
  53944. configurable: true
  53945. });
  53946. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53947. get: function () {
  53948. return this._isVisibilityBoxLocked;
  53949. },
  53950. /**
  53951. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53952. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53953. */
  53954. set: function (val) {
  53955. this._isVisibilityBoxLocked = val;
  53956. this.mesh.getBoundingInfo().isLocked = val;
  53957. },
  53958. enumerable: true,
  53959. configurable: true
  53960. });
  53961. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53962. // getters
  53963. get: function () {
  53964. return this._computeParticleRotation;
  53965. },
  53966. // Optimizer setters
  53967. /**
  53968. * Tells to `setParticles()` to compute the particle rotations or not.
  53969. * Default value : true. The SPS is faster when it's set to false.
  53970. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53971. */
  53972. set: function (val) {
  53973. this._computeParticleRotation = val;
  53974. },
  53975. enumerable: true,
  53976. configurable: true
  53977. });
  53978. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53979. get: function () {
  53980. return this._computeParticleColor;
  53981. },
  53982. /**
  53983. * Tells to `setParticles()` to compute the particle colors or not.
  53984. * Default value : true. The SPS is faster when it's set to false.
  53985. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53986. */
  53987. set: function (val) {
  53988. this._computeParticleColor = val;
  53989. },
  53990. enumerable: true,
  53991. configurable: true
  53992. });
  53993. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53994. get: function () {
  53995. return this._computeParticleTexture;
  53996. },
  53997. /**
  53998. * Tells to `setParticles()` to compute the particle textures or not.
  53999. * Default value : true. The SPS is faster when it's set to false.
  54000. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54001. */
  54002. set: function (val) {
  54003. this._computeParticleTexture = val;
  54004. },
  54005. enumerable: true,
  54006. configurable: true
  54007. });
  54008. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54009. get: function () {
  54010. return this._computeParticleVertex;
  54011. },
  54012. /**
  54013. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54014. * Default value : false. The SPS is faster when it's set to false.
  54015. * Note : the particle custom vertex positions aren't stored values.
  54016. */
  54017. set: function (val) {
  54018. this._computeParticleVertex = val;
  54019. },
  54020. enumerable: true,
  54021. configurable: true
  54022. });
  54023. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54024. get: function () {
  54025. return this._computeBoundingBox;
  54026. },
  54027. /**
  54028. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54029. */
  54030. set: function (val) {
  54031. this._computeBoundingBox = val;
  54032. },
  54033. enumerable: true,
  54034. configurable: true
  54035. });
  54036. // =======================================================================
  54037. // Particle behavior logic
  54038. // these following methods may be overwritten by the user to fit his needs
  54039. /**
  54040. * This function does nothing. It may be overwritten to set all the particle first values.
  54041. * The SPS doesn't call this function, you may have to call it by your own.
  54042. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54043. */
  54044. SolidParticleSystem.prototype.initParticles = function () {
  54045. };
  54046. /**
  54047. * This function does nothing. It may be overwritten to recycle a particle.
  54048. * The SPS doesn't call this function, you may have to call it by your own.
  54049. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54050. */
  54051. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54052. return particle;
  54053. };
  54054. /**
  54055. * Updates a particle : this function should be overwritten by the user.
  54056. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54057. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54058. * ex : just set a particle position or velocity and recycle conditions
  54059. */
  54060. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54061. return particle;
  54062. };
  54063. /**
  54064. * Updates a vertex of a particle : it can be overwritten by the user.
  54065. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54066. * @param particle the current particle
  54067. * @param vertex the current index of the current particle
  54068. * @param pt the index of the current vertex in the particle shape
  54069. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54070. * ex : just set a vertex particle position
  54071. */
  54072. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54073. return vertex;
  54074. };
  54075. /**
  54076. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54077. * This does nothing and may be overwritten by the user.
  54078. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54079. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54080. * @param update the boolean update value actually passed to setParticles()
  54081. */
  54082. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54083. };
  54084. /**
  54085. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54086. * This will be passed three parameters.
  54087. * This does nothing and may be overwritten by the user.
  54088. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54089. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54090. * @param update the boolean update value actually passed to setParticles()
  54091. */
  54092. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54093. };
  54094. return SolidParticleSystem;
  54095. }());
  54096. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54097. })(BABYLON || (BABYLON = {}));
  54098. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54099. var BABYLON;
  54100. (function (BABYLON) {
  54101. var Internals;
  54102. (function (Internals) {
  54103. var FileFaceOrientation = (function () {
  54104. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  54105. this.name = name;
  54106. this.worldAxisForNormal = worldAxisForNormal;
  54107. this.worldAxisForFileX = worldAxisForFileX;
  54108. this.worldAxisForFileY = worldAxisForFileY;
  54109. }
  54110. return FileFaceOrientation;
  54111. }());
  54112. ;
  54113. /**
  54114. * Helper class dealing with the extraction of spherical polynomial dataArray
  54115. * from a cube map.
  54116. */
  54117. var CubeMapToSphericalPolynomialTools = (function () {
  54118. function CubeMapToSphericalPolynomialTools() {
  54119. }
  54120. /**
  54121. * Converts a cubemap to the according Spherical Polynomial data.
  54122. * This extracts the first 3 orders only as they are the only one used in the lighting.
  54123. *
  54124. * @param cubeInfo The Cube map to extract the information from.
  54125. * @return The Spherical Polynomial data.
  54126. */
  54127. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  54128. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  54129. var totalSolidAngle = 0.0;
  54130. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  54131. var du = 2.0 / cubeInfo.size;
  54132. var dv = du;
  54133. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  54134. var minUV = du * 0.5 - 1.0;
  54135. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  54136. var fileFace = this.FileFaces[faceIndex];
  54137. var dataArray = cubeInfo[fileFace.name];
  54138. var v = minUV;
  54139. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  54140. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  54141. // Because SP is still linear, so summation is fine in that basis.
  54142. for (var y = 0; y < cubeInfo.size; y++) {
  54143. var u = minUV;
  54144. for (var x = 0; x < cubeInfo.size; x++) {
  54145. // World direction (not normalised)
  54146. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  54147. worldDirection.normalize();
  54148. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  54149. if (1) {
  54150. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  54151. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  54152. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  54153. var color = new BABYLON.Color3(r, g, b);
  54154. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54155. }
  54156. else {
  54157. if (faceIndex == 0) {
  54158. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54159. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54160. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54161. }
  54162. else if (faceIndex == 1) {
  54163. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54164. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54165. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54166. }
  54167. else if (faceIndex == 2) {
  54168. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54169. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54170. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54171. }
  54172. else if (faceIndex == 3) {
  54173. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54174. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54175. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  54176. }
  54177. else if (faceIndex == 4) {
  54178. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  54179. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  54180. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54181. }
  54182. else if (faceIndex == 5) {
  54183. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  54184. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  54185. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  54186. }
  54187. 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]);
  54188. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  54189. }
  54190. totalSolidAngle += deltaSolidAngle;
  54191. u += du;
  54192. }
  54193. v += dv;
  54194. }
  54195. }
  54196. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  54197. var correction = correctSolidAngle / totalSolidAngle;
  54198. sphericalHarmonics.scale(correction);
  54199. // Additionally scale by pi -- audit needed
  54200. sphericalHarmonics.scale(1.0 / Math.PI);
  54201. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  54202. };
  54203. return CubeMapToSphericalPolynomialTools;
  54204. }());
  54205. CubeMapToSphericalPolynomialTools.FileFaces = [
  54206. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  54207. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  54208. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  54209. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  54210. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  54211. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  54212. ];
  54213. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  54214. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54215. })(BABYLON || (BABYLON = {}));
  54216. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  54217. var BABYLON;
  54218. (function (BABYLON) {
  54219. var Internals;
  54220. (function (Internals) {
  54221. /**
  54222. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  54223. */
  54224. var PanoramaToCubeMapTools = (function () {
  54225. function PanoramaToCubeMapTools() {
  54226. }
  54227. /**
  54228. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  54229. *
  54230. * @param float32Array The source data.
  54231. * @param inputWidth The width of the input panorama.
  54232. * @param inputhHeight The height of the input panorama.
  54233. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  54234. * @return The cubemap data
  54235. */
  54236. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  54237. if (!float32Array) {
  54238. throw "ConvertPanoramaToCubemap: input cannot be null";
  54239. }
  54240. if (float32Array.length != inputWidth * inputHeight * 3) {
  54241. throw "ConvertPanoramaToCubemap: input size is wrong";
  54242. }
  54243. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  54244. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  54245. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  54246. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  54247. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  54248. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  54249. return {
  54250. front: textureFront,
  54251. back: textureBack,
  54252. left: textureLeft,
  54253. right: textureRight,
  54254. up: textureUp,
  54255. down: textureDown,
  54256. size: size
  54257. };
  54258. };
  54259. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  54260. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  54261. var textureArray = new Float32Array(buffer);
  54262. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  54263. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  54264. var dy = 1 / texSize;
  54265. var fy = 0;
  54266. for (var y = 0; y < texSize; y++) {
  54267. var xv1 = faceData[0];
  54268. var xv2 = faceData[2];
  54269. for (var x = 0; x < texSize; x++) {
  54270. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  54271. v.normalize();
  54272. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  54273. // 3 channels per pixels
  54274. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  54275. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  54276. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  54277. xv1 = xv1.add(rotDX1);
  54278. xv2 = xv2.add(rotDX2);
  54279. }
  54280. fy += dy;
  54281. }
  54282. return textureArray;
  54283. };
  54284. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  54285. var theta = Math.atan2(vDir.z, vDir.x);
  54286. var phi = Math.acos(vDir.y);
  54287. while (theta < -Math.PI)
  54288. theta += 2 * Math.PI;
  54289. while (theta > Math.PI)
  54290. theta -= 2 * Math.PI;
  54291. var dx = theta / Math.PI;
  54292. var dy = phi / Math.PI;
  54293. // recenter.
  54294. dx = dx * 0.5 + 0.5;
  54295. var px = Math.round(dx * inputWidth);
  54296. if (px < 0)
  54297. px = 0;
  54298. else if (px >= inputWidth)
  54299. px = inputWidth - 1;
  54300. var py = Math.round(dy * inputHeight);
  54301. if (py < 0)
  54302. py = 0;
  54303. else if (py >= inputHeight)
  54304. py = inputHeight - 1;
  54305. var inputY = (inputHeight - py - 1);
  54306. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  54307. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  54308. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  54309. return {
  54310. r: r,
  54311. g: g,
  54312. b: b
  54313. };
  54314. };
  54315. return PanoramaToCubeMapTools;
  54316. }());
  54317. PanoramaToCubeMapTools.FACE_FRONT = [
  54318. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54319. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54320. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54321. new BABYLON.Vector3(1.0, 1.0, -1.0)
  54322. ];
  54323. PanoramaToCubeMapTools.FACE_BACK = [
  54324. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54325. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54326. new BABYLON.Vector3(1.0, 1.0, 1.0),
  54327. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  54328. ];
  54329. PanoramaToCubeMapTools.FACE_RIGHT = [
  54330. new BABYLON.Vector3(1.0, -1.0, -1.0),
  54331. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54332. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54333. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54334. ];
  54335. PanoramaToCubeMapTools.FACE_LEFT = [
  54336. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54337. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54338. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54339. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  54340. ];
  54341. PanoramaToCubeMapTools.FACE_DOWN = [
  54342. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  54343. new BABYLON.Vector3(1.0, 1.0, -1.0),
  54344. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  54345. new BABYLON.Vector3(1.0, 1.0, 1.0)
  54346. ];
  54347. PanoramaToCubeMapTools.FACE_UP = [
  54348. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  54349. new BABYLON.Vector3(1.0, -1.0, 1.0),
  54350. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  54351. new BABYLON.Vector3(1.0, -1.0, -1.0)
  54352. ];
  54353. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  54354. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54355. })(BABYLON || (BABYLON = {}));
  54356. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  54357. var BABYLON;
  54358. (function (BABYLON) {
  54359. var Internals;
  54360. (function (Internals) {
  54361. ;
  54362. /**
  54363. * This groups tools to convert HDR texture to native colors array.
  54364. */
  54365. var HDRTools = (function () {
  54366. function HDRTools() {
  54367. }
  54368. HDRTools.Ldexp = function (mantissa, exponent) {
  54369. if (exponent > 1023) {
  54370. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  54371. }
  54372. if (exponent < -1074) {
  54373. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  54374. }
  54375. return mantissa * Math.pow(2, exponent);
  54376. };
  54377. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  54378. if (exponent > 0) {
  54379. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  54380. float32array[index + 0] = red * exponent;
  54381. float32array[index + 1] = green * exponent;
  54382. float32array[index + 2] = blue * exponent;
  54383. }
  54384. else {
  54385. float32array[index + 0] = 0;
  54386. float32array[index + 1] = 0;
  54387. float32array[index + 2] = 0;
  54388. }
  54389. };
  54390. HDRTools.readStringLine = function (uint8array, startIndex) {
  54391. var line = "";
  54392. var character = "";
  54393. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  54394. character = String.fromCharCode(uint8array[i]);
  54395. if (character == "\n") {
  54396. break;
  54397. }
  54398. line += character;
  54399. }
  54400. return line;
  54401. };
  54402. /**
  54403. * Reads header information from an RGBE texture stored in a native array.
  54404. * More information on this format are available here:
  54405. * https://en.wikipedia.org/wiki/RGBE_image_format
  54406. *
  54407. * @param uint8array The binary file stored in native array.
  54408. * @return The header information.
  54409. */
  54410. HDRTools.RGBE_ReadHeader = function (uint8array) {
  54411. var height = 0;
  54412. var width = 0;
  54413. var line = this.readStringLine(uint8array, 0);
  54414. if (line[0] != '#' || line[1] != '?') {
  54415. throw "Bad HDR Format.";
  54416. }
  54417. var endOfHeader = false;
  54418. var findFormat = false;
  54419. var lineIndex = 0;
  54420. do {
  54421. lineIndex += (line.length + 1);
  54422. line = this.readStringLine(uint8array, lineIndex);
  54423. if (line == "FORMAT=32-bit_rle_rgbe") {
  54424. findFormat = true;
  54425. }
  54426. else if (line.length == 0) {
  54427. endOfHeader = true;
  54428. }
  54429. } while (!endOfHeader);
  54430. if (!findFormat) {
  54431. throw "HDR Bad header format, unsupported FORMAT";
  54432. }
  54433. lineIndex += (line.length + 1);
  54434. line = this.readStringLine(uint8array, lineIndex);
  54435. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  54436. var match = sizeRegexp.exec(line);
  54437. // TODO. Support +Y and -X if needed.
  54438. if (match.length < 3) {
  54439. throw "HDR Bad header format, no size";
  54440. }
  54441. width = parseInt(match[2]);
  54442. height = parseInt(match[1]);
  54443. if (width < 8 || width > 0x7fff) {
  54444. throw "HDR Bad header format, unsupported size";
  54445. }
  54446. lineIndex += (line.length + 1);
  54447. return {
  54448. height: height,
  54449. width: width,
  54450. dataPosition: lineIndex
  54451. };
  54452. };
  54453. /**
  54454. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  54455. * This RGBE texture needs to store the information as a panorama.
  54456. *
  54457. * More information on this format are available here:
  54458. * https://en.wikipedia.org/wiki/RGBE_image_format
  54459. *
  54460. * @param buffer The binary file stored in an array buffer.
  54461. * @param size The expected size of the extracted cubemap.
  54462. * @return The Cube Map information.
  54463. */
  54464. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  54465. var uint8array = new Uint8Array(buffer);
  54466. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  54467. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54468. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  54469. return cubeMapData;
  54470. };
  54471. /**
  54472. * Returns the pixels data extracted from an RGBE texture.
  54473. * This pixels will be stored left to right up to down in the R G B order in one array.
  54474. *
  54475. * More information on this format are available here:
  54476. * https://en.wikipedia.org/wiki/RGBE_image_format
  54477. *
  54478. * @param uint8array The binary file stored in an array buffer.
  54479. * @param hdrInfo The header information of the file.
  54480. * @return The pixels data in RGB right to left up to down order.
  54481. */
  54482. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  54483. // Keep for multi format supports.
  54484. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  54485. };
  54486. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  54487. var num_scanlines = hdrInfo.height;
  54488. var scanline_width = hdrInfo.width;
  54489. var a, b, c, d, count;
  54490. var dataIndex = hdrInfo.dataPosition;
  54491. var index = 0, endIndex = 0, i = 0;
  54492. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  54493. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  54494. // 3 channels of 4 bytes per pixel in float.
  54495. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  54496. var resultArray = new Float32Array(resultBuffer);
  54497. // read in each successive scanline
  54498. while (num_scanlines > 0) {
  54499. a = uint8array[dataIndex++];
  54500. b = uint8array[dataIndex++];
  54501. c = uint8array[dataIndex++];
  54502. d = uint8array[dataIndex++];
  54503. if (a != 2 || b != 2 || (c & 0x80)) {
  54504. // this file is not run length encoded
  54505. throw "HDR Bad header format, not RLE";
  54506. }
  54507. if (((c << 8) | d) != scanline_width) {
  54508. throw "HDR Bad header format, wrong scan line width";
  54509. }
  54510. index = 0;
  54511. // read each of the four channels for the scanline into the buffer
  54512. for (i = 0; i < 4; i++) {
  54513. endIndex = (i + 1) * scanline_width;
  54514. while (index < endIndex) {
  54515. a = uint8array[dataIndex++];
  54516. b = uint8array[dataIndex++];
  54517. if (a > 128) {
  54518. // a run of the same value
  54519. count = a - 128;
  54520. if ((count == 0) || (count > endIndex - index)) {
  54521. throw "HDR Bad Format, bad scanline data (run)";
  54522. }
  54523. while (count-- > 0) {
  54524. scanLineArray[index++] = b;
  54525. }
  54526. }
  54527. else {
  54528. // a non-run
  54529. count = a;
  54530. if ((count == 0) || (count > endIndex - index)) {
  54531. throw "HDR Bad Format, bad scanline data (non-run)";
  54532. }
  54533. scanLineArray[index++] = b;
  54534. if (--count > 0) {
  54535. for (var j = 0; j < count; j++) {
  54536. scanLineArray[index++] = uint8array[dataIndex++];
  54537. }
  54538. }
  54539. }
  54540. }
  54541. }
  54542. // now convert data from buffer into floats
  54543. for (i = 0; i < scanline_width; i++) {
  54544. a = scanLineArray[i];
  54545. b = scanLineArray[i + scanline_width];
  54546. c = scanLineArray[i + 2 * scanline_width];
  54547. d = scanLineArray[i + 3 * scanline_width];
  54548. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  54549. }
  54550. num_scanlines--;
  54551. }
  54552. return resultArray;
  54553. };
  54554. return HDRTools;
  54555. }());
  54556. Internals.HDRTools = HDRTools;
  54557. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54558. })(BABYLON || (BABYLON = {}));
  54559. //# sourceMappingURL=babylon.tools.hdr.js.map
  54560. //_______________________________________________________________
  54561. // Extracted from CubeMapGen:
  54562. // https://code.google.com/archive/p/cubemapgen/
  54563. //
  54564. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54565. //_______________________________________________________________
  54566. var BABYLON;
  54567. (function (BABYLON) {
  54568. var Internals;
  54569. (function (Internals) {
  54570. /**
  54571. * The bounding box information used during the conversion process.
  54572. */
  54573. var CMGBoundinBox = (function () {
  54574. function CMGBoundinBox() {
  54575. this.min = new BABYLON.Vector3(0, 0, 0);
  54576. this.max = new BABYLON.Vector3(0, 0, 0);
  54577. this.clear();
  54578. }
  54579. CMGBoundinBox.prototype.clear = function () {
  54580. this.min.x = CMGBoundinBox.MAX;
  54581. this.min.y = CMGBoundinBox.MAX;
  54582. this.min.z = CMGBoundinBox.MAX;
  54583. this.max.x = CMGBoundinBox.MIN;
  54584. this.max.y = CMGBoundinBox.MIN;
  54585. this.max.z = CMGBoundinBox.MIN;
  54586. };
  54587. CMGBoundinBox.prototype.augment = function (x, y, z) {
  54588. this.min.x = Math.min(this.min.x, x);
  54589. this.min.y = Math.min(this.min.y, y);
  54590. this.min.z = Math.min(this.min.z, z);
  54591. this.max.x = Math.max(this.max.x, x);
  54592. this.max.y = Math.max(this.max.y, y);
  54593. this.max.z = Math.max(this.max.z, z);
  54594. };
  54595. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  54596. this.min.x = Math.max(this.min.x, x);
  54597. this.min.y = Math.max(this.min.y, y);
  54598. this.min.z = Math.max(this.min.z, z);
  54599. };
  54600. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  54601. this.max.x = Math.min(this.max.x, x);
  54602. this.max.y = Math.min(this.max.y, y);
  54603. this.max.z = Math.min(this.max.z, z);
  54604. };
  54605. CMGBoundinBox.prototype.empty = function () {
  54606. if ((this.min.x > this.max.y) ||
  54607. (this.min.y > this.max.y) ||
  54608. (this.min.z > this.max.y)) {
  54609. return true;
  54610. }
  54611. else {
  54612. return false;
  54613. }
  54614. };
  54615. return CMGBoundinBox;
  54616. }());
  54617. CMGBoundinBox.MAX = Number.MAX_VALUE;
  54618. CMGBoundinBox.MIN = Number.MIN_VALUE;
  54619. /**
  54620. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  54621. * required by the glossinees of a material.
  54622. *
  54623. * This only supports the cosine drop power as well as Warp fixup generation method.
  54624. *
  54625. * This is using the process from CubeMapGen described here:
  54626. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  54627. */
  54628. var PMREMGenerator = (function () {
  54629. /**
  54630. * Constructor of the generator.
  54631. *
  54632. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  54633. * @param inputSize The size of the cubemap faces
  54634. * @param outputSize The size of the output cubemap faces
  54635. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  54636. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  54637. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  54638. * @param specularPower The max specular level of the desired cubemap
  54639. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  54640. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  54641. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  54642. */
  54643. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  54644. this.input = input;
  54645. this.inputSize = inputSize;
  54646. this.outputSize = outputSize;
  54647. this.maxNumMipLevels = maxNumMipLevels;
  54648. this.numChannels = numChannels;
  54649. this.isFloat = isFloat;
  54650. this.specularPower = specularPower;
  54651. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  54652. this.excludeBase = excludeBase;
  54653. this.fixup = fixup;
  54654. this._outputSurface = [];
  54655. this._numMipLevels = 0;
  54656. }
  54657. /**
  54658. * Launches the filter process and return the result.
  54659. *
  54660. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  54661. */
  54662. PMREMGenerator.prototype.filterCubeMap = function () {
  54663. // Init cubemap processor
  54664. this.init();
  54665. // Filters the cubemap
  54666. this.filterCubeMapMipChain();
  54667. // Returns the filtered mips.
  54668. return this._outputSurface;
  54669. };
  54670. PMREMGenerator.prototype.init = function () {
  54671. var i;
  54672. var j;
  54673. var mipLevelSize;
  54674. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  54675. if (this.maxNumMipLevels == 0) {
  54676. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  54677. }
  54678. //first miplevel size
  54679. mipLevelSize = this.outputSize;
  54680. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  54681. for (j = 0; j < this.maxNumMipLevels; j++) {
  54682. this._outputSurface.length++;
  54683. this._outputSurface[j] = [];
  54684. //Iterate over faces for output images
  54685. for (i = 0; i < 6; i++) {
  54686. this._outputSurface[j].length++;
  54687. // Initializes a new array for the output.
  54688. if (this.isFloat) {
  54689. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54690. }
  54691. else {
  54692. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  54693. }
  54694. }
  54695. //next mip level is half size
  54696. mipLevelSize >>= 1;
  54697. this._numMipLevels++;
  54698. //terminate if mip chain becomes too small
  54699. if (mipLevelSize == 0) {
  54700. this.maxNumMipLevels = j;
  54701. return;
  54702. }
  54703. }
  54704. };
  54705. //--------------------------------------------------------------------------------------
  54706. //Cube map filtering and mip chain generation.
  54707. // the cube map filtereing is specified using a number of parameters:
  54708. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  54709. // indicates the region of the hemisphere to filter over for each tap.
  54710. //
  54711. // Note that the top mip level is also a filtered version of the original input images
  54712. // as well in order to create mip chains for diffuse environment illumination.
  54713. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  54714. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  54715. //
  54716. // Then the mip angle used to genreate the next level of the mip chain from the first level
  54717. // is a_InitialMipAngle
  54718. //
  54719. // The angle for the subsequent levels of the mip chain are specified by their parents
  54720. // filtering angle and a per-level scale and bias
  54721. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  54722. //
  54723. //--------------------------------------------------------------------------------------
  54724. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  54725. // First, take count of the lighting model to modify SpecularPower
  54726. // 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;
  54727. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  54728. //Cone angle start (for generating subsequent mip levels)
  54729. var currentSpecularPower = this.specularPower;
  54730. //Build filter lookup tables based on the source miplevel size
  54731. this.precomputeFilterLookupTables(this.inputSize);
  54732. // Note that we need to filter the first level before generating mipmap
  54733. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  54734. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  54735. // TODO : Write a function to copy and scale the base mipmap in output
  54736. // I am just lazy here and just put a high specular power value, and do some if.
  54737. if (this.excludeBase && (levelIndex == 0)) {
  54738. // 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).
  54739. currentSpecularPower = 100000.0;
  54740. }
  54741. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  54742. var srcCubeImage = this.input;
  54743. var dstCubeImage = this._outputSurface[levelIndex];
  54744. var dstSize = this.outputSize >> levelIndex;
  54745. // Compute required angle.
  54746. var angle = this.getBaseFilterAngle(currentSpecularPower);
  54747. // filter cube surfaces
  54748. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  54749. // fix seams
  54750. if (this.fixup) {
  54751. this.fixupCubeEdges(dstCubeImage, dstSize);
  54752. }
  54753. // Decrease the specular power to generate the mipmap chain
  54754. // TODO : Use another method for Exclude (see first comment at start of the function
  54755. if (this.excludeBase && (levelIndex == 0)) {
  54756. currentSpecularPower = this.specularPower;
  54757. }
  54758. currentSpecularPower *= this.cosinePowerDropPerMip;
  54759. }
  54760. };
  54761. //--------------------------------------------------------------------------------------
  54762. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  54763. // It allow to optimize the texel to access base on the specular power.
  54764. //--------------------------------------------------------------------------------------
  54765. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  54766. // We want to find the alpha such that:
  54767. // cos(alpha)^cosinePower = epsilon
  54768. // That's: acos(epsilon^(1/cosinePower))
  54769. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  54770. var angle = 180.0;
  54771. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  54772. angle *= 180.0 / Math.PI; // Convert to degree
  54773. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  54774. return angle;
  54775. };
  54776. //--------------------------------------------------------------------------------------
  54777. //Builds the following lookup tables prior to filtering:
  54778. // -normalizer cube map
  54779. // -tap weight lookup table
  54780. //
  54781. //--------------------------------------------------------------------------------------
  54782. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  54783. var srcTexelAngle;
  54784. var iCubeFace;
  54785. //clear pre-existing normalizer cube map
  54786. this._normCubeMap = [];
  54787. //Normalized vectors per cubeface and per-texel solid angle
  54788. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  54789. };
  54790. //--------------------------------------------------------------------------------------
  54791. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  54792. //
  54793. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  54794. //
  54795. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  54796. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  54797. // below
  54798. //--------------------------------------------------------------------------------------
  54799. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  54800. var iCubeFace;
  54801. var u;
  54802. var v;
  54803. //iterate over cube faces
  54804. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  54805. //First three channels for norm cube, and last channel for solid angle
  54806. this._normCubeMap.push(new Float32Array(size * size * 4));
  54807. //fast texture walk, build normalizer cube map
  54808. var facesData = this.input[iCubeFace];
  54809. for (v = 0; v < size; v++) {
  54810. for (u = 0; u < size; u++) {
  54811. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  54812. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  54813. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  54814. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  54815. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  54816. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  54817. }
  54818. }
  54819. }
  54820. };
  54821. //--------------------------------------------------------------------------------------
  54822. // Convert cubemap face texel coordinates and face idx to 3D vector
  54823. // note the U and V coords are integer coords and range from 0 to size-1
  54824. // this routine can be used to generate a normalizer cube map
  54825. //--------------------------------------------------------------------------------------
  54826. // SL BEGIN
  54827. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  54828. var nvcU;
  54829. var nvcV;
  54830. var tempVec;
  54831. // Change from original AMD code
  54832. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54833. // + 0.5f is for texel center addressing
  54834. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  54835. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  54836. // warp fixup
  54837. if (fixup && size > 1) {
  54838. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  54839. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  54840. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  54841. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  54842. }
  54843. // Get current vector
  54844. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  54845. // U contribution
  54846. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54847. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  54848. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  54849. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  54850. // V contribution and Sum
  54851. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54852. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  54853. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  54854. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  54855. //add face axis
  54856. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  54857. PMREMGenerator._vectorTemp.x += faceAxis[0];
  54858. PMREMGenerator._vectorTemp.y += faceAxis[1];
  54859. PMREMGenerator._vectorTemp.z += faceAxis[2];
  54860. //normalize vector
  54861. PMREMGenerator._vectorTemp.normalize();
  54862. return PMREMGenerator._vectorTemp;
  54863. };
  54864. //--------------------------------------------------------------------------------------
  54865. // Convert 3D vector to cubemap face texel coordinates and face idx
  54866. // note the U and V coords are integer coords and range from 0 to size-1
  54867. // this routine can be used to generate a normalizer cube map
  54868. //
  54869. // returns face IDX and texel coords
  54870. //--------------------------------------------------------------------------------------
  54871. // SL BEGIN
  54872. /*
  54873. Mapping Texture Coordinates to Cube Map Faces
  54874. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  54875. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  54876. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  54877. map arrangement in Pixar's RenderMan package.
  54878. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  54879. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  54880. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  54881. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  54882. the major axis direction). The target column in the table below explains how the major axis direction
  54883. maps to the 2D image of a particular cube map target.
  54884. major axis
  54885. direction target sc tc ma
  54886. ---------- --------------------------------- --- --- ---
  54887. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  54888. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  54889. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  54890. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  54891. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  54892. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  54893. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  54894. an updated (s,t) is calculated as follows
  54895. s = ( sc/|ma| + 1 ) / 2
  54896. t = ( tc/|ma| + 1 ) / 2
  54897. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  54898. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  54899. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  54900. */
  54901. // Note this method return U and V in range from 0 to size-1
  54902. // SL END
  54903. // Store the information in vector3 for convenience (faceindex, u, v)
  54904. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  54905. var maxCoord;
  54906. var faceIdx;
  54907. //absolute value 3
  54908. var absX = Math.abs(x);
  54909. var absY = Math.abs(y);
  54910. var absZ = Math.abs(z);
  54911. if (absX >= absY && absX >= absZ) {
  54912. maxCoord = absX;
  54913. if (x >= 0) {
  54914. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  54915. }
  54916. else {
  54917. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  54918. }
  54919. }
  54920. else if (absY >= absX && absY >= absZ) {
  54921. maxCoord = absY;
  54922. if (y >= 0) {
  54923. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  54924. }
  54925. else {
  54926. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  54927. }
  54928. }
  54929. else {
  54930. maxCoord = absZ;
  54931. if (z >= 0) {
  54932. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  54933. }
  54934. else {
  54935. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  54936. }
  54937. }
  54938. //divide through by max coord so face vector lies on cube face
  54939. var scale = 1 / maxCoord;
  54940. x *= scale;
  54941. y *= scale;
  54942. z *= scale;
  54943. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  54944. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  54945. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  54946. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  54947. // Modify original AMD code to return value from 0 to Size - 1
  54948. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  54949. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  54950. PMREMGenerator._vectorTemp.x = faceIdx;
  54951. PMREMGenerator._vectorTemp.y = u;
  54952. PMREMGenerator._vectorTemp.z = v;
  54953. return PMREMGenerator._vectorTemp;
  54954. };
  54955. //--------------------------------------------------------------------------------------
  54956. //Original code from Ignacio CastaÒo
  54957. // This formula is from Manne ÷hrstrˆm's thesis.
  54958. // Take two coordiantes in the range [-1, 1] that define a portion of a
  54959. // cube face and return the area of the projection of that portion on the
  54960. // surface of the sphere.
  54961. //--------------------------------------------------------------------------------------
  54962. PMREMGenerator.prototype.areaElement = function (x, y) {
  54963. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  54964. };
  54965. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  54966. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  54967. // (+ 0.5f is for texel center addressing)
  54968. u = (2.0 * (u + 0.5) / size) - 1.0;
  54969. v = (2.0 * (v + 0.5) / size) - 1.0;
  54970. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  54971. var invResolution = 1.0 / size;
  54972. // U and V are the -1..1 texture coordinate on the current face.
  54973. // Get projected area for this texel
  54974. var x0 = u - invResolution;
  54975. var y0 = v - invResolution;
  54976. var x1 = u + invResolution;
  54977. var y1 = v + invResolution;
  54978. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  54979. return solidAngle;
  54980. };
  54981. //--------------------------------------------------------------------------------------
  54982. //The key to the speed of these filtering routines is to quickly define a per-face
  54983. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  54984. // Later these pixels are selectively processed based on their dot products to see if
  54985. // they reside within the filtering cone.
  54986. //
  54987. //This is done by computing the smallest per-texel angle to get a conservative estimate
  54988. // of the number of texels needed to be covered in width and height order to filter the
  54989. // region. the bounding box for the center taps face is defined first, and if the
  54990. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  54991. // defined next
  54992. //--------------------------------------------------------------------------------------
  54993. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  54994. // note that pixels within these regions may be rejected
  54995. // based on the anlge
  54996. var iCubeFace;
  54997. var u;
  54998. var v;
  54999. // bounding box per face to specify region to process
  55000. var filterExtents = [];
  55001. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55002. filterExtents.push(new CMGBoundinBox());
  55003. }
  55004. // min angle a src texel can cover (in degrees)
  55005. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55006. // angle about center tap to define filter cone
  55007. // filter angle is 1/2 the cone angle
  55008. var filterAngle = filterConeAngle / 2.0;
  55009. //ensure filter angle is larger than a texel
  55010. if (filterAngle < srcTexelAngle) {
  55011. filterAngle = srcTexelAngle;
  55012. }
  55013. //ensure filter cone is always smaller than the hemisphere
  55014. if (filterAngle > 90.0) {
  55015. filterAngle = 90.0;
  55016. }
  55017. // the maximum number of texels in 1D the filter cone angle will cover
  55018. // used to determine bounding box size for filter extents
  55019. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55020. // ensure conservative region always covers at least one texel
  55021. if (filterSize < 1) {
  55022. filterSize = 1;
  55023. }
  55024. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55025. // reside within the cone angle
  55026. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55027. // process required faces
  55028. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55029. //iterate over dst cube map face texel
  55030. for (v = 0; v < dstSize; v++) {
  55031. for (u = 0; u < dstSize; u++) {
  55032. //get center tap direction
  55033. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55034. //clear old per-face filter extents
  55035. this.clearFilterExtents(filterExtents);
  55036. //define per-face filter extents
  55037. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55038. //perform filtering of src faces using filter extents
  55039. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55040. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55041. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55042. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55043. }
  55044. }
  55045. }
  55046. };
  55047. //--------------------------------------------------------------------------------------
  55048. //Clear filter extents for the 6 cube map faces
  55049. //--------------------------------------------------------------------------------------
  55050. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55051. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55052. filterExtents[iCubeFaces].clear();
  55053. }
  55054. };
  55055. //--------------------------------------------------------------------------------------
  55056. //Define per-face bounding box filter extents
  55057. //
  55058. // These define conservative texel regions in each of the faces the filter can possibly
  55059. // process. When the pixels in the regions are actually processed, the dot product
  55060. // between the tap vector and the center tap vector is used to determine the weight of
  55061. // the tap and whether or not the tap is within the cone.
  55062. //
  55063. //--------------------------------------------------------------------------------------
  55064. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55065. //neighboring face and bleed over amount, and width of BBOX for
  55066. // left, right, top, and bottom edges of this face
  55067. var bleedOverAmount = [0, 0, 0, 0];
  55068. var bleedOverBBoxMin = [0, 0, 0, 0];
  55069. var bleedOverBBoxMax = [0, 0, 0, 0];
  55070. var neighborFace;
  55071. var neighborEdge;
  55072. var oppositeFaceIdx;
  55073. //get face idx, and u, v info from center tap dir
  55074. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  55075. var faceIdx = result.x;
  55076. var u = result.y;
  55077. var v = result.z;
  55078. //define bbox size within face
  55079. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  55080. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  55081. filterExtents[faceIdx].clampMin(0, 0, 0);
  55082. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  55083. //u and v extent in face corresponding to center tap
  55084. var minU = filterExtents[faceIdx].min.x;
  55085. var minV = filterExtents[faceIdx].min.y;
  55086. var maxU = filterExtents[faceIdx].max.x;
  55087. var maxV = filterExtents[faceIdx].max.y;
  55088. //bleed over amounts for face across u=0 edge (left)
  55089. bleedOverAmount[0] = (bboxSize - u);
  55090. bleedOverBBoxMin[0] = minV;
  55091. bleedOverBBoxMax[0] = maxV;
  55092. //bleed over amounts for face across u=1 edge (right)
  55093. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  55094. bleedOverBBoxMin[1] = minV;
  55095. bleedOverBBoxMax[1] = maxV;
  55096. //bleed over to face across v=0 edge (up)
  55097. bleedOverAmount[2] = (bboxSize - v);
  55098. bleedOverBBoxMin[2] = minU;
  55099. bleedOverBBoxMax[2] = maxU;
  55100. //bleed over to face across v=1 edge (down)
  55101. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  55102. bleedOverBBoxMin[3] = minU;
  55103. bleedOverBBoxMax[3] = maxU;
  55104. //compute bleed over regions in neighboring faces
  55105. for (var i = 0; i < 4; i++) {
  55106. if (bleedOverAmount[i] > 0) {
  55107. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  55108. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  55109. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  55110. // be flipped: the cases are
  55111. // if a left edge mates with a left or bottom edge on the neighbor
  55112. // if a top edge mates with a top or right edge on the neighbor
  55113. // if a right edge mates with a right or top edge on the neighbor
  55114. // if a bottom edge mates with a bottom or left edge on the neighbor
  55115. //Seeing as the edges are enumerated as follows
  55116. // left =0
  55117. // right =1
  55118. // top =2
  55119. // bottom =3
  55120. //
  55121. // so if the edge enums are the same, or the sum of the enums == 3,
  55122. // the bbox needs to be flipped
  55123. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  55124. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  55125. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  55126. }
  55127. //The way the bounding box is extended onto the neighboring face
  55128. // depends on which edge of neighboring face abuts with this one
  55129. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  55130. case PMREMGenerator.CP_EDGE_LEFT:
  55131. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  55132. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55133. break;
  55134. case PMREMGenerator.CP_EDGE_RIGHT:
  55135. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  55136. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  55137. break;
  55138. case PMREMGenerator.CP_EDGE_TOP:
  55139. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  55140. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  55141. break;
  55142. case PMREMGenerator.CP_EDGE_BOTTOM:
  55143. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  55144. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  55145. break;
  55146. }
  55147. //clamp filter extents in non-center tap faces to remain within surface
  55148. filterExtents[neighborFace].clampMin(0, 0, 0);
  55149. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  55150. }
  55151. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  55152. // from the center tap face, then process the opposite face entirely for now.
  55153. //Note that the cases in which this happens, what usually happens is that
  55154. // more than one edge bleeds onto the opposite face, and the bounding box
  55155. // encompasses the entire cube map face.
  55156. if (bleedOverAmount[i] > srcSize) {
  55157. //determine opposite face
  55158. switch (faceIdx) {
  55159. case PMREMGenerator.CP_FACE_X_POS:
  55160. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55161. break;
  55162. case PMREMGenerator.CP_FACE_X_NEG:
  55163. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  55164. break;
  55165. case PMREMGenerator.CP_FACE_Y_POS:
  55166. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55167. break;
  55168. case PMREMGenerator.CP_FACE_Y_NEG:
  55169. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55170. break;
  55171. case PMREMGenerator.CP_FACE_Z_POS:
  55172. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55173. break;
  55174. case PMREMGenerator.CP_FACE_Z_NEG:
  55175. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55176. break;
  55177. default:
  55178. break;
  55179. }
  55180. //just encompass entire face for now
  55181. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  55182. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  55183. }
  55184. }
  55185. };
  55186. //--------------------------------------------------------------------------------------
  55187. //ProcessFilterExtents
  55188. // Process bounding box in each cube face
  55189. //
  55190. //--------------------------------------------------------------------------------------
  55191. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  55192. //accumulators are 64-bit floats in order to have the precision needed
  55193. // over a summation of a large number of pixels
  55194. var dstAccum = [0, 0, 0, 0];
  55195. var weightAccum = 0;
  55196. var k = 0;
  55197. var nSrcChannels = this.numChannels;
  55198. // norm cube map and srcCubeMap have same face width
  55199. var faceWidth = srcSize;
  55200. //amount to add to pointer to move to next scanline in images
  55201. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  55202. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  55203. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  55204. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  55205. // iterate over cubefaces
  55206. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  55207. //if bbox is non empty
  55208. if (!filterExtents[iFaceIdx].empty()) {
  55209. var uStart = filterExtents[iFaceIdx].min.x;
  55210. var vStart = filterExtents[iFaceIdx].min.y;
  55211. var uEnd = filterExtents[iFaceIdx].max.x;
  55212. var vEnd = filterExtents[iFaceIdx].max.y;
  55213. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  55214. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  55215. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  55216. for (var v = vStart; v <= vEnd; v++) {
  55217. var normCubeRowWalk = 0;
  55218. var srcCubeRowWalk = 0;
  55219. for (var u = uStart; u <= uEnd; u++) {
  55220. //pointer to direction in cube map associated with texel
  55221. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  55222. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  55223. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  55224. //check dot product to see if texel is within cone
  55225. var tapDotProd = texelVectX * centerTapDir.x +
  55226. texelVectY * centerTapDir.y +
  55227. texelVectZ * centerTapDir.z;
  55228. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  55229. //solid angle stored in 4th channel of normalizer/solid angle cube map
  55230. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  55231. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  55232. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  55233. // so just adding one to specularpower do the trick.
  55234. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  55235. //iterate over channels
  55236. for (k = 0; k < nSrcChannels; k++) {
  55237. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  55238. srcCubeRowWalk++;
  55239. }
  55240. weightAccum += weight; //accumulate weight
  55241. }
  55242. else {
  55243. //step across source pixel
  55244. srcCubeRowWalk += nSrcChannels;
  55245. }
  55246. normCubeRowWalk += 4; // 4 channels per norm cube map.
  55247. }
  55248. startIndexNormCubeMap += normCubePitch;
  55249. startIndexSrcCubeMap += srcCubePitch;
  55250. }
  55251. }
  55252. }
  55253. //divide through by weights if weight is non zero
  55254. if (weightAccum != 0.0) {
  55255. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  55256. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  55257. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  55258. if (this.numChannels > 3) {
  55259. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  55260. }
  55261. }
  55262. else {
  55263. // otherwise sample nearest
  55264. // get face idx and u, v texel coordinate in face
  55265. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  55266. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  55267. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  55268. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  55269. if (this.numChannels > 3) {
  55270. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  55271. }
  55272. }
  55273. return PMREMGenerator._vectorTemp;
  55274. };
  55275. //--------------------------------------------------------------------------------------
  55276. // Fixup cube edges
  55277. //
  55278. // average texels on cube map faces across the edges
  55279. // WARP/BENT Method Only.
  55280. //--------------------------------------------------------------------------------------
  55281. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  55282. var k;
  55283. var j;
  55284. var i;
  55285. var iFace;
  55286. var iCorner = 0;
  55287. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  55288. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  55289. // note that if functionality to filter across the three texels for each corner, then
  55290. //indexed by corner and face idx. the array contains the face the start points belongs to.
  55291. var cornerPtr = [
  55292. [[], [], []],
  55293. [[], [], []],
  55294. [[], [], []],
  55295. [[], [], []],
  55296. [[], [], []],
  55297. [[], [], []],
  55298. [[], [], []],
  55299. [[], [], []]
  55300. ];
  55301. //if there is no fixup, or fixup width = 0, do nothing
  55302. if (cubeMapSize < 1) {
  55303. return;
  55304. }
  55305. //special case 1x1 cubemap, average face colors
  55306. if (cubeMapSize == 1) {
  55307. //iterate over channels
  55308. for (k = 0; k < this.numChannels; k++) {
  55309. var accum = 0.0;
  55310. //iterate over faces to accumulate face colors
  55311. for (iFace = 0; iFace < 6; iFace++) {
  55312. accum += cubeMap[iFace][k];
  55313. }
  55314. //compute average over 6 face colors
  55315. accum /= 6.0;
  55316. //iterate over faces to distribute face colors
  55317. for (iFace = 0; iFace < 6; iFace++) {
  55318. cubeMap[iFace][k] = accum;
  55319. }
  55320. }
  55321. return;
  55322. }
  55323. //iterate over faces to collect list of corner texel pointers
  55324. for (iFace = 0; iFace < 6; iFace++) {
  55325. //the 4 corner pointers for this face
  55326. faceCornerStartIndicies[0] = [iFace, 0];
  55327. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  55328. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  55329. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  55330. //iterate over face corners to collect cube corner pointers
  55331. for (iCorner = 0; iCorner < 4; iCorner++) {
  55332. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  55333. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  55334. cornerNumPtrs[corner]++;
  55335. }
  55336. }
  55337. //iterate over corners to average across corner tap values
  55338. for (iCorner = 0; iCorner < 8; iCorner++) {
  55339. for (k = 0; k < this.numChannels; k++) {
  55340. var cornerTapAccum = 0.0;
  55341. //iterate over corner texels and average results
  55342. for (i = 0; i < 3; i++) {
  55343. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  55344. }
  55345. //divide by 3 to compute average of corner tap values
  55346. cornerTapAccum *= (1.0 / 3.0);
  55347. //iterate over corner texels and average results
  55348. for (i = 0; i < 3; i++) {
  55349. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  55350. }
  55351. }
  55352. }
  55353. //iterate over the twelve edges of the cube to average across edges
  55354. for (i = 0; i < 12; i++) {
  55355. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  55356. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  55357. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  55358. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  55359. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  55360. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  55361. var edgeWalk = 0;
  55362. var neighborEdgeWalk = 0;
  55363. //Determine walking pointers based on edge type
  55364. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  55365. switch (edge) {
  55366. case PMREMGenerator.CP_EDGE_LEFT:
  55367. // no change to faceEdgeStartPtr
  55368. edgeWalk = this.numChannels * cubeMapSize;
  55369. break;
  55370. case PMREMGenerator.CP_EDGE_RIGHT:
  55371. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55372. edgeWalk = this.numChannels * cubeMapSize;
  55373. break;
  55374. case PMREMGenerator.CP_EDGE_TOP:
  55375. // no change to faceEdgeStartPtr
  55376. edgeWalk = this.numChannels;
  55377. break;
  55378. case PMREMGenerator.CP_EDGE_BOTTOM:
  55379. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55380. edgeWalk = this.numChannels;
  55381. break;
  55382. }
  55383. //For certain types of edge abutments, the neighbor edge walk needs to
  55384. // be flipped: the cases are
  55385. // if a left edge mates with a left or bottom edge on the neighbor
  55386. // if a top edge mates with a top or right edge on the neighbor
  55387. // if a right edge mates with a right or top edge on the neighbor
  55388. // if a bottom edge mates with a bottom or left edge on the neighbor
  55389. //Seeing as the edges are enumerated as follows
  55390. // left =0
  55391. // right =1
  55392. // top =2
  55393. // bottom =3
  55394. //
  55395. //If the edge enums are the same, or the sum of the enums == 3,
  55396. // the neighbor edge walk needs to be flipped
  55397. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  55398. switch (neighborEdge) {
  55399. case PMREMGenerator.CP_EDGE_LEFT:
  55400. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  55401. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55402. break;
  55403. case PMREMGenerator.CP_EDGE_RIGHT:
  55404. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55405. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  55406. break;
  55407. case PMREMGenerator.CP_EDGE_TOP:
  55408. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55409. neighborEdgeWalk = -this.numChannels;
  55410. break;
  55411. case PMREMGenerator.CP_EDGE_BOTTOM:
  55412. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  55413. neighborEdgeWalk = -this.numChannels;
  55414. break;
  55415. }
  55416. }
  55417. else {
  55418. //swapped direction neighbor edge walk
  55419. switch (neighborEdge) {
  55420. case PMREMGenerator.CP_EDGE_LEFT:
  55421. //no change to neighborEdgeStartPtr for this case since it points
  55422. // to the upper left corner already
  55423. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55424. break;
  55425. case PMREMGenerator.CP_EDGE_RIGHT:
  55426. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  55427. neighborEdgeWalk = this.numChannels * cubeMapSize;
  55428. break;
  55429. case PMREMGenerator.CP_EDGE_TOP:
  55430. //no change to neighborEdgeStartPtr for this case since it points
  55431. // to the upper left corner already
  55432. neighborEdgeWalk = this.numChannels;
  55433. break;
  55434. case PMREMGenerator.CP_EDGE_BOTTOM:
  55435. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  55436. neighborEdgeWalk = this.numChannels;
  55437. break;
  55438. }
  55439. }
  55440. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  55441. //nearby neighborhood
  55442. //step ahead one texel on edge
  55443. edgeStartIndex += edgeWalk;
  55444. neighborEdgeStartIndex += neighborEdgeWalk;
  55445. // note that this loop does not process the corner texels, since they have already been
  55446. // averaged across faces across earlier
  55447. for (j = 1; j < (cubeMapSize - 1); j++) {
  55448. //for each set of taps along edge, average them
  55449. // and rewrite the results into the edges
  55450. for (k = 0; k < this.numChannels; k++) {
  55451. var edgeTap = cubeMap[face][edgeStartIndex + k];
  55452. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  55453. //compute average of tap intensity values
  55454. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  55455. //propagate average of taps to edge taps
  55456. cubeMap[face][edgeStartIndex + k] = avgTap;
  55457. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  55458. }
  55459. edgeStartIndex += edgeWalk;
  55460. neighborEdgeStartIndex += neighborEdgeWalk;
  55461. }
  55462. }
  55463. };
  55464. return PMREMGenerator;
  55465. }());
  55466. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  55467. PMREMGenerator.CP_UDIR = 0;
  55468. PMREMGenerator.CP_VDIR = 1;
  55469. PMREMGenerator.CP_FACEAXIS = 2;
  55470. //used to index cube faces
  55471. PMREMGenerator.CP_FACE_X_POS = 0;
  55472. PMREMGenerator.CP_FACE_X_NEG = 1;
  55473. PMREMGenerator.CP_FACE_Y_POS = 2;
  55474. PMREMGenerator.CP_FACE_Y_NEG = 3;
  55475. PMREMGenerator.CP_FACE_Z_POS = 4;
  55476. PMREMGenerator.CP_FACE_Z_NEG = 5;
  55477. //used to index image edges
  55478. // NOTE.. the actual number corresponding to the edge is important
  55479. // do not change these, or the code will break
  55480. //
  55481. // CP_EDGE_LEFT is u = 0
  55482. // CP_EDGE_RIGHT is u = width-1
  55483. // CP_EDGE_TOP is v = 0
  55484. // CP_EDGE_BOTTOM is v = height-1
  55485. PMREMGenerator.CP_EDGE_LEFT = 0;
  55486. PMREMGenerator.CP_EDGE_RIGHT = 1;
  55487. PMREMGenerator.CP_EDGE_TOP = 2;
  55488. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  55489. //corners of CUBE map (P or N specifys if it corresponds to the
  55490. // positive or negative direction each of X, Y, and Z
  55491. PMREMGenerator.CP_CORNER_NNN = 0;
  55492. PMREMGenerator.CP_CORNER_NNP = 1;
  55493. PMREMGenerator.CP_CORNER_NPN = 2;
  55494. PMREMGenerator.CP_CORNER_NPP = 3;
  55495. PMREMGenerator.CP_CORNER_PNN = 4;
  55496. PMREMGenerator.CP_CORNER_PNP = 5;
  55497. PMREMGenerator.CP_CORNER_PPN = 6;
  55498. PMREMGenerator.CP_CORNER_PPP = 7;
  55499. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  55500. //3x2 matrices that map cube map indexing vectors in 3d
  55501. // (after face selection and divide through by the
  55502. // _ABSOLUTE VALUE_ of the max coord)
  55503. // into NVC space
  55504. //Note this currently assumes the D3D cube face ordering and orientation
  55505. PMREMGenerator._sgFace2DMapping = [
  55506. //XPOS face
  55507. [[0, 0, -1],
  55508. [0, -1, 0],
  55509. [1, 0, 0]],
  55510. //XNEG face
  55511. [[0, 0, 1],
  55512. [0, -1, 0],
  55513. [-1, 0, 0]],
  55514. //YPOS face
  55515. [[1, 0, 0],
  55516. [0, 0, 1],
  55517. [0, 1, 0]],
  55518. //YNEG face
  55519. [[1, 0, 0],
  55520. [0, 0, -1],
  55521. [0, -1, 0]],
  55522. //ZPOS face
  55523. [[1, 0, 0],
  55524. [0, -1, 0],
  55525. [0, 0, 1]],
  55526. //ZNEG face
  55527. [[-1, 0, 0],
  55528. [0, -1, 0],
  55529. [0, 0, -1]],
  55530. ];
  55531. //------------------------------------------------------------------------------
  55532. // D3D cube map face specification
  55533. // mapping from 3D x,y,z cube map lookup coordinates
  55534. // to 2D within face u,v coordinates
  55535. //
  55536. // --------------------> U direction
  55537. // | (within-face texture space)
  55538. // | _____
  55539. // | | |
  55540. // | | +Y |
  55541. // | _____|_____|_____ _____
  55542. // | | | | | |
  55543. // | | -X | +Z | +X | -Z |
  55544. // | |_____|_____|_____|_____|
  55545. // | | |
  55546. // | | -Y |
  55547. // | |_____|
  55548. // |
  55549. // v V direction
  55550. // (within-face texture space)
  55551. //------------------------------------------------------------------------------
  55552. //Information about neighbors and how texture coorrdinates change across faces
  55553. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  55554. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  55555. //Note this currently assumes the D3D cube face ordering and orientation
  55556. PMREMGenerator._sgCubeNgh = [
  55557. //XPOS face
  55558. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55559. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55560. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55561. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  55562. //XNEG face
  55563. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55564. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  55565. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  55566. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  55567. //YPOS face
  55568. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55569. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55570. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55571. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  55572. //YNEG face
  55573. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55574. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55575. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55576. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  55577. //ZPOS face
  55578. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55579. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55580. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55581. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  55582. //ZNEG face
  55583. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55584. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55585. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  55586. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  55587. ];
  55588. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  55589. // this table is used to average over the edges.
  55590. PMREMGenerator._sgCubeEdgeList = [
  55591. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  55592. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  55593. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  55594. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55595. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  55596. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  55597. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  55598. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  55599. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  55600. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  55601. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  55602. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  55603. ];
  55604. //Information about which of the 8 cube corners are correspond to the
  55605. // the 4 corners in each cube face
  55606. // the order is upper left, upper right, lower left, lower right
  55607. PMREMGenerator._sgCubeCornerList = [
  55608. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  55609. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  55610. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  55611. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  55612. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  55613. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  55614. ];
  55615. Internals.PMREMGenerator = PMREMGenerator;
  55616. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55617. })(BABYLON || (BABYLON = {}));
  55618. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  55619. var BABYLON;
  55620. (function (BABYLON) {
  55621. /**
  55622. * This represents a texture coming from an HDR input.
  55623. *
  55624. * The only supported format is currently panorama picture stored in RGBE format.
  55625. * Example of such files can be found on HDRLib: http://hdrlib.com/
  55626. */
  55627. var HDRCubeTexture = (function (_super) {
  55628. __extends(HDRCubeTexture, _super);
  55629. /**
  55630. * Instantiates an HDRTexture from the following parameters.
  55631. *
  55632. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  55633. * @param scene The scene the texture will be used in
  55634. * @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.
  55635. * @param noMipmap Forces to not generate the mipmap if true
  55636. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  55637. * @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)
  55638. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  55639. */
  55640. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  55641. if (noMipmap === void 0) { noMipmap = false; }
  55642. if (generateHarmonics === void 0) { generateHarmonics = true; }
  55643. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  55644. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  55645. if (onLoad === void 0) { onLoad = null; }
  55646. if (onError === void 0) { onError = null; }
  55647. var _this = _super.call(this, scene) || this;
  55648. _this._useInGammaSpace = false;
  55649. _this._generateHarmonics = true;
  55650. _this._isBABYLONPreprocessed = false;
  55651. _this._onLoad = null;
  55652. _this._onError = null;
  55653. /**
  55654. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  55655. */
  55656. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  55657. /**
  55658. * The spherical polynomial data extracted from the texture.
  55659. */
  55660. _this.sphericalPolynomial = null;
  55661. /**
  55662. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  55663. * This is usefull at run time to apply the good shader.
  55664. */
  55665. _this.isPMREM = false;
  55666. if (!url) {
  55667. return _this;
  55668. }
  55669. _this.name = url;
  55670. _this.url = url;
  55671. _this.hasAlpha = false;
  55672. _this.isCube = true;
  55673. _this._textureMatrix = BABYLON.Matrix.Identity();
  55674. _this._onLoad = onLoad;
  55675. _this._onError = onError;
  55676. if (size) {
  55677. _this._isBABYLONPreprocessed = false;
  55678. _this._noMipmap = noMipmap;
  55679. _this._size = size;
  55680. _this._useInGammaSpace = useInGammaSpace;
  55681. _this._usePMREMGenerator = usePMREMGenerator &&
  55682. scene.getEngine().getCaps().textureLOD &&
  55683. _this.getScene().getEngine().getCaps().textureFloat &&
  55684. !_this._useInGammaSpace;
  55685. }
  55686. else {
  55687. _this._isBABYLONPreprocessed = true;
  55688. _this._noMipmap = false;
  55689. _this._useInGammaSpace = false;
  55690. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  55691. _this.getScene().getEngine().getCaps().textureFloat &&
  55692. !_this._useInGammaSpace;
  55693. }
  55694. _this.isPMREM = _this._usePMREMGenerator;
  55695. _this._texture = _this._getFromCache(url, _this._noMipmap);
  55696. if (!_this._texture) {
  55697. if (!scene.useDelayedTextureLoading) {
  55698. _this.loadTexture();
  55699. }
  55700. else {
  55701. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  55702. }
  55703. }
  55704. return _this;
  55705. }
  55706. /**
  55707. * Occurs when the file is a preprocessed .babylon.hdr file.
  55708. */
  55709. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  55710. var _this = this;
  55711. var mipLevels = 0;
  55712. var floatArrayView = null;
  55713. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  55714. var mips = [];
  55715. var startIndex = 30;
  55716. for (var level = 0; level < mipLevels; level++) {
  55717. mips.push([]);
  55718. // Fill each pixel of the mip level.
  55719. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  55720. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55721. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  55722. mips[level].push(faceData);
  55723. startIndex += faceSize;
  55724. }
  55725. }
  55726. return mips;
  55727. } : null;
  55728. var callback = function (buffer) {
  55729. // Create Native Array Views
  55730. var intArrayView = new Int32Array(buffer);
  55731. floatArrayView = new Float32Array(buffer);
  55732. // Fill header.
  55733. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  55734. _this._size = intArrayView[1]; // CubeMap max mip face size.
  55735. // Update Texture Information.
  55736. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  55737. // Fill polynomial information.
  55738. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  55739. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  55740. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  55741. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  55742. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  55743. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  55744. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  55745. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  55746. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  55747. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  55748. // Fill pixel data.
  55749. mipLevels = intArrayView[29]; // Number of mip levels.
  55750. var startIndex = 30;
  55751. var data = [];
  55752. var faceSize = Math.pow(_this._size, 2) * 3;
  55753. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55754. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  55755. startIndex += faceSize;
  55756. }
  55757. var results = [];
  55758. var byteArray = null;
  55759. // Push each faces.
  55760. for (var k = 0; k < 6; k++) {
  55761. var dataFace = null;
  55762. // If special cases.
  55763. if (!mipmapGenerator) {
  55764. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  55765. dataFace = data[j];
  55766. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55767. // 3 channels of 1 bytes per pixel in bytes.
  55768. var byteBuffer = new ArrayBuffer(faceSize);
  55769. byteArray = new Uint8Array(byteBuffer);
  55770. }
  55771. for (var i = 0; i < _this._size * _this._size; i++) {
  55772. // Put in gamma space if requested.
  55773. if (_this._useInGammaSpace) {
  55774. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55775. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55776. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55777. }
  55778. // Convert to int texture for fallback.
  55779. if (byteArray) {
  55780. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55781. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55782. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55783. // May use luminance instead if the result is not accurate.
  55784. var max = Math.max(Math.max(r, g), b);
  55785. if (max > 255) {
  55786. var scale = 255 / max;
  55787. r *= scale;
  55788. g *= scale;
  55789. b *= scale;
  55790. }
  55791. byteArray[(i * 3) + 0] = r;
  55792. byteArray[(i * 3) + 1] = g;
  55793. byteArray[(i * 3) + 2] = b;
  55794. }
  55795. }
  55796. }
  55797. else {
  55798. dataFace = data[k];
  55799. }
  55800. // Fill the array accordingly.
  55801. if (byteArray) {
  55802. results.push(byteArray);
  55803. }
  55804. else {
  55805. results.push(dataFace);
  55806. }
  55807. }
  55808. return results;
  55809. };
  55810. 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);
  55811. };
  55812. /**
  55813. * Occurs when the file is raw .hdr file.
  55814. */
  55815. HDRCubeTexture.prototype.loadHDRTexture = function () {
  55816. var _this = this;
  55817. var callback = function (buffer) {
  55818. // Extract the raw linear data.
  55819. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  55820. // Generate harmonics if needed.
  55821. if (_this._generateHarmonics) {
  55822. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  55823. }
  55824. var results = [];
  55825. var byteArray = null;
  55826. // Push each faces.
  55827. for (var j = 0; j < 6; j++) {
  55828. // Create uintarray fallback.
  55829. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  55830. // 3 channels of 1 bytes per pixel in bytes.
  55831. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  55832. byteArray = new Uint8Array(byteBuffer);
  55833. }
  55834. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  55835. // If special cases.
  55836. if (_this._useInGammaSpace || byteArray) {
  55837. for (var i = 0; i < _this._size * _this._size; i++) {
  55838. // Put in gamma space if requested.
  55839. if (_this._useInGammaSpace) {
  55840. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  55841. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  55842. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  55843. }
  55844. // Convert to int texture for fallback.
  55845. if (byteArray) {
  55846. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  55847. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  55848. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  55849. // May use luminance instead if the result is not accurate.
  55850. var max = Math.max(Math.max(r, g), b);
  55851. if (max > 255) {
  55852. var scale = 255 / max;
  55853. r *= scale;
  55854. g *= scale;
  55855. b *= scale;
  55856. }
  55857. byteArray[(i * 3) + 0] = r;
  55858. byteArray[(i * 3) + 1] = g;
  55859. byteArray[(i * 3) + 2] = b;
  55860. }
  55861. }
  55862. }
  55863. if (byteArray) {
  55864. results.push(byteArray);
  55865. }
  55866. else {
  55867. results.push(dataFace);
  55868. }
  55869. }
  55870. return results;
  55871. };
  55872. var mipmapGenerator = null;
  55873. if (!this._noMipmap &&
  55874. this._usePMREMGenerator) {
  55875. mipmapGenerator = function (data) {
  55876. // Custom setup of the generator matching with the PBR shader values.
  55877. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  55878. return generator.filterCubeMap();
  55879. };
  55880. }
  55881. 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);
  55882. };
  55883. /**
  55884. * Starts the loading process of the texture.
  55885. */
  55886. HDRCubeTexture.prototype.loadTexture = function () {
  55887. if (this._isBABYLONPreprocessed) {
  55888. this.loadBabylonTexture();
  55889. }
  55890. else {
  55891. this.loadHDRTexture();
  55892. }
  55893. };
  55894. HDRCubeTexture.prototype.clone = function () {
  55895. var size = this._isBABYLONPreprocessed ? null : this._size;
  55896. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  55897. // Base texture
  55898. newTexture.level = this.level;
  55899. newTexture.wrapU = this.wrapU;
  55900. newTexture.wrapV = this.wrapV;
  55901. newTexture.coordinatesIndex = this.coordinatesIndex;
  55902. newTexture.coordinatesMode = this.coordinatesMode;
  55903. return newTexture;
  55904. };
  55905. // Methods
  55906. HDRCubeTexture.prototype.delayLoad = function () {
  55907. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  55908. return;
  55909. }
  55910. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  55911. this._texture = this._getFromCache(this.url, this._noMipmap);
  55912. if (!this._texture) {
  55913. this.loadTexture();
  55914. }
  55915. };
  55916. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  55917. return this._textureMatrix;
  55918. };
  55919. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  55920. var texture = null;
  55921. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  55922. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  55923. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  55924. texture.name = parsedTexture.name;
  55925. texture.hasAlpha = parsedTexture.hasAlpha;
  55926. texture.level = parsedTexture.level;
  55927. texture.coordinatesMode = parsedTexture.coordinatesMode;
  55928. }
  55929. return texture;
  55930. };
  55931. HDRCubeTexture.prototype.serialize = function () {
  55932. if (!this.name) {
  55933. return null;
  55934. }
  55935. var serializationObject = {};
  55936. serializationObject.name = this.name;
  55937. serializationObject.hasAlpha = this.hasAlpha;
  55938. serializationObject.isCube = true;
  55939. serializationObject.level = this.level;
  55940. serializationObject.size = this._size;
  55941. serializationObject.coordinatesMode = this.coordinatesMode;
  55942. serializationObject.useInGammaSpace = this._useInGammaSpace;
  55943. serializationObject.generateHarmonics = this._generateHarmonics;
  55944. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  55945. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  55946. serializationObject.customType = "BABYLON.HDRCubeTexture";
  55947. serializationObject.noMipmap = this._noMipmap;
  55948. return serializationObject;
  55949. };
  55950. /**
  55951. * Saves as a file the data contained in the texture in a binary format.
  55952. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55953. * as the spherical used in the lighting.
  55954. * @param url The HDR file url.
  55955. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55956. * @param onError Method called if any error happens during download.
  55957. * @return The packed binary data.
  55958. */
  55959. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  55960. if (onError === void 0) { onError = null; }
  55961. var callback = function (buffer) {
  55962. var data = new Blob([buffer], { type: 'application/octet-stream' });
  55963. // Returns a URL you can use as a href.
  55964. var objUrl = window.URL.createObjectURL(data);
  55965. // Simulates a link to it and click to dowload.
  55966. var a = document.createElement("a");
  55967. document.body.appendChild(a);
  55968. a.style.display = "none";
  55969. a.href = objUrl;
  55970. a.download = "envmap.babylon.hdr";
  55971. a.click();
  55972. };
  55973. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  55974. };
  55975. /**
  55976. * Serializes the data contained in the texture in a binary format.
  55977. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  55978. * as the spherical used in the lighting.
  55979. * @param url The HDR file url.
  55980. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  55981. * @param onError Method called if any error happens during download.
  55982. * @return The packed binary data.
  55983. */
  55984. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  55985. if (onError === void 0) { onError = null; }
  55986. // Needs the url tho create the texture.
  55987. if (!url) {
  55988. return null;
  55989. }
  55990. // Check Power of two size.
  55991. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  55992. return null;
  55993. }
  55994. var getDataCallback = function (dataBuffer) {
  55995. // Extract the raw linear data.
  55996. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  55997. // Generate harmonics if needed.
  55998. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  55999. // Generate seamless faces
  56000. var mipGeneratorArray = [];
  56001. // Data are known to be in +X +Y +Z -X -Y -Z
  56002. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56003. mipGeneratorArray.push(cubeData.right); // +X
  56004. mipGeneratorArray.push(cubeData.left); // -X
  56005. mipGeneratorArray.push(cubeData.up); // +Y
  56006. mipGeneratorArray.push(cubeData.down); // -Y
  56007. mipGeneratorArray.push(cubeData.front); // +Z
  56008. mipGeneratorArray.push(cubeData.back); // -Z
  56009. // Custom setup of the generator matching with the PBR shader values.
  56010. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56011. var mippedData = generator.filterCubeMap();
  56012. // Compute required byte length.
  56013. var byteLength = 1 * 4; // Raw Data Version int32.
  56014. byteLength += 4; // CubeMap max mip face size int32.
  56015. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56016. // Add data size.
  56017. byteLength += 4; // Number of mip levels int32.
  56018. for (var level = 0; level < mippedData.length; level++) {
  56019. var mipSize = size >> level;
  56020. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56021. }
  56022. // Prepare binary structure.
  56023. var buffer = new ArrayBuffer(byteLength);
  56024. var intArrayView = new Int32Array(buffer);
  56025. var floatArrayView = new Float32Array(buffer);
  56026. // Fill header.
  56027. intArrayView[0] = 1; // Version 1.
  56028. intArrayView[1] = size; // CubeMap max mip face size.
  56029. // Fill polynomial information.
  56030. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56031. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56032. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56033. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56034. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56035. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56036. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56037. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56038. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56039. // Fill pixel data.
  56040. intArrayView[29] = mippedData.length; // Number of mip levels.
  56041. var startIndex = 30;
  56042. for (var level = 0; level < mippedData.length; level++) {
  56043. // Fill each pixel of the mip level.
  56044. var faceSize = Math.pow(size >> level, 2) * 3;
  56045. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56046. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56047. startIndex += faceSize;
  56048. }
  56049. }
  56050. // Callback.
  56051. callback(buffer);
  56052. };
  56053. // Download and process.
  56054. BABYLON.Tools.LoadFile(url, function (data) {
  56055. getDataCallback(data);
  56056. }, null, null, true, onError);
  56057. };
  56058. return HDRCubeTexture;
  56059. }(BABYLON.BaseTexture));
  56060. HDRCubeTexture._facesMapping = [
  56061. "right",
  56062. "up",
  56063. "front",
  56064. "left",
  56065. "down",
  56066. "back"
  56067. ];
  56068. BABYLON.HDRCubeTexture = HDRCubeTexture;
  56069. })(BABYLON || (BABYLON = {}));
  56070. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  56071. var BABYLON;
  56072. (function (BABYLON) {
  56073. var Debug;
  56074. (function (Debug) {
  56075. /**
  56076. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56077. */
  56078. var SkeletonViewer = (function () {
  56079. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56080. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56081. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56082. this.skeleton = skeleton;
  56083. this.mesh = mesh;
  56084. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56085. this.renderingGroupId = renderingGroupId;
  56086. this.color = BABYLON.Color3.White();
  56087. this._debugLines = [];
  56088. this._isEnabled = false;
  56089. this._scene = scene;
  56090. this.update();
  56091. this._renderFunction = this.update.bind(this);
  56092. }
  56093. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56094. get: function () {
  56095. return this._isEnabled;
  56096. },
  56097. set: function (value) {
  56098. if (this._isEnabled === value) {
  56099. return;
  56100. }
  56101. this._isEnabled = value;
  56102. if (value) {
  56103. this._scene.registerBeforeRender(this._renderFunction);
  56104. }
  56105. else {
  56106. this._scene.unregisterBeforeRender(this._renderFunction);
  56107. }
  56108. },
  56109. enumerable: true,
  56110. configurable: true
  56111. });
  56112. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56113. if (x === void 0) { x = 0; }
  56114. if (y === void 0) { y = 0; }
  56115. if (z === void 0) { z = 0; }
  56116. var tmat = BABYLON.Tmp.Matrix[0];
  56117. var parentBone = bone.getParent();
  56118. tmat.copyFrom(bone.getLocalMatrix());
  56119. if (x !== 0 || y !== 0 || z !== 0) {
  56120. var tmat2 = BABYLON.Tmp.Matrix[1];
  56121. BABYLON.Matrix.IdentityToRef(tmat2);
  56122. tmat2.m[12] = x;
  56123. tmat2.m[13] = y;
  56124. tmat2.m[14] = z;
  56125. tmat2.multiplyToRef(tmat, tmat);
  56126. }
  56127. if (parentBone) {
  56128. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56129. }
  56130. tmat.multiplyToRef(meshMat, tmat);
  56131. position.x = tmat.m[12];
  56132. position.y = tmat.m[13];
  56133. position.z = tmat.m[14];
  56134. };
  56135. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56136. var len = bones.length;
  56137. for (var i = 0; i < len; i++) {
  56138. var bone = bones[i];
  56139. var points = this._debugLines[i];
  56140. if (!points) {
  56141. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56142. this._debugLines[i] = points;
  56143. }
  56144. this._getBonePosition(points[0], bone, meshMat);
  56145. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56146. }
  56147. };
  56148. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56149. var len = bones.length;
  56150. var boneNum = 0;
  56151. for (var i = len - 1; i >= 0; i--) {
  56152. var childBone = bones[i];
  56153. var parentBone = childBone.getParent();
  56154. if (!parentBone) {
  56155. continue;
  56156. }
  56157. var points = this._debugLines[boneNum];
  56158. if (!points) {
  56159. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56160. this._debugLines[boneNum] = points;
  56161. }
  56162. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56163. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56164. boneNum++;
  56165. }
  56166. };
  56167. SkeletonViewer.prototype.update = function () {
  56168. if (this.autoUpdateBonesMatrices) {
  56169. this.skeleton.computeAbsoluteTransforms();
  56170. }
  56171. if (this.skeleton.bones[0].length === undefined) {
  56172. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56173. }
  56174. else {
  56175. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56176. }
  56177. if (!this._debugMesh) {
  56178. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56179. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56180. }
  56181. else {
  56182. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56183. }
  56184. this._debugMesh.color = this.color;
  56185. };
  56186. SkeletonViewer.prototype.dispose = function () {
  56187. if (this._debugMesh) {
  56188. this.isEnabled = false;
  56189. this._debugMesh.dispose();
  56190. this._debugMesh = null;
  56191. }
  56192. };
  56193. return SkeletonViewer;
  56194. }());
  56195. Debug.SkeletonViewer = SkeletonViewer;
  56196. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56197. })(BABYLON || (BABYLON = {}));
  56198. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56199. var BABYLON;
  56200. (function (BABYLON) {
  56201. var Debug;
  56202. (function (Debug) {
  56203. var AxesViewer = (function () {
  56204. function AxesViewer(scene, scaleLines) {
  56205. if (scaleLines === void 0) { scaleLines = 1; }
  56206. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56207. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56208. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56209. this.scaleLines = 1;
  56210. this.scaleLines = scaleLines;
  56211. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  56212. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  56213. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  56214. this._xmesh.renderingGroupId = 2;
  56215. this._ymesh.renderingGroupId = 2;
  56216. this._zmesh.renderingGroupId = 2;
  56217. this._xmesh.material.checkReadyOnlyOnce = true;
  56218. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  56219. this._ymesh.material.checkReadyOnlyOnce = true;
  56220. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  56221. this._zmesh.material.checkReadyOnlyOnce = true;
  56222. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  56223. this.scene = scene;
  56224. }
  56225. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  56226. var scaleLines = this.scaleLines;
  56227. var point1 = this._xline[0];
  56228. var point2 = this._xline[1];
  56229. point1.x = position.x;
  56230. point1.y = position.y;
  56231. point1.z = position.z;
  56232. point2.x = point1.x + xaxis.x * scaleLines;
  56233. point2.y = point1.y + xaxis.y * scaleLines;
  56234. point2.z = point1.z + xaxis.z * scaleLines;
  56235. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  56236. point1 = this._yline[0];
  56237. point2 = this._yline[1];
  56238. point1.x = position.x;
  56239. point1.y = position.y;
  56240. point1.z = position.z;
  56241. point2.x = point1.x + yaxis.x * scaleLines;
  56242. point2.y = point1.y + yaxis.y * scaleLines;
  56243. point2.z = point1.z + yaxis.z * scaleLines;
  56244. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  56245. point1 = this._zline[0];
  56246. point2 = this._zline[1];
  56247. point1.x = position.x;
  56248. point1.y = position.y;
  56249. point1.z = position.z;
  56250. point2.x = point1.x + zaxis.x * scaleLines;
  56251. point2.y = point1.y + zaxis.y * scaleLines;
  56252. point2.z = point1.z + zaxis.z * scaleLines;
  56253. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  56254. };
  56255. AxesViewer.prototype.dispose = function () {
  56256. if (this._xmesh) {
  56257. this._xmesh.dispose();
  56258. this._ymesh.dispose();
  56259. this._zmesh.dispose();
  56260. this._xmesh = null;
  56261. this._ymesh = null;
  56262. this._zmesh = null;
  56263. this._xline = null;
  56264. this._yline = null;
  56265. this._zline = null;
  56266. this.scene = null;
  56267. }
  56268. };
  56269. return AxesViewer;
  56270. }());
  56271. Debug.AxesViewer = AxesViewer;
  56272. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56273. })(BABYLON || (BABYLON = {}));
  56274. //# sourceMappingURL=babylon.axesViewer.js.map
  56275. var BABYLON;
  56276. (function (BABYLON) {
  56277. var Debug;
  56278. (function (Debug) {
  56279. var BoneAxesViewer = (function (_super) {
  56280. __extends(BoneAxesViewer, _super);
  56281. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  56282. if (scaleLines === void 0) { scaleLines = 1; }
  56283. var _this = _super.call(this, scene, scaleLines) || this;
  56284. _this.pos = BABYLON.Vector3.Zero();
  56285. _this.xaxis = BABYLON.Vector3.Zero();
  56286. _this.yaxis = BABYLON.Vector3.Zero();
  56287. _this.zaxis = BABYLON.Vector3.Zero();
  56288. _this.mesh = mesh;
  56289. _this.bone = bone;
  56290. return _this;
  56291. }
  56292. BoneAxesViewer.prototype.update = function () {
  56293. var bone = this.bone;
  56294. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  56295. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  56296. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  56297. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  56298. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  56299. };
  56300. BoneAxesViewer.prototype.dispose = function () {
  56301. if (this.pos) {
  56302. this.pos = null;
  56303. this.xaxis = null;
  56304. this.yaxis = null;
  56305. this.zaxis = null;
  56306. this.mesh = null;
  56307. this.bone = null;
  56308. _super.prototype.dispose.call(this);
  56309. }
  56310. };
  56311. return BoneAxesViewer;
  56312. }(Debug.AxesViewer));
  56313. Debug.BoneAxesViewer = BoneAxesViewer;
  56314. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56315. })(BABYLON || (BABYLON = {}));
  56316. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  56317. var BABYLON;
  56318. (function (BABYLON) {
  56319. /**
  56320. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  56321. * It can help converting any input color in a desired output one. This can then be used to create effects
  56322. * from sepia, black and white to sixties or futuristic rendering...
  56323. *
  56324. * The only supported format is currently 3dl.
  56325. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  56326. */
  56327. var ColorGradingTexture = (function (_super) {
  56328. __extends(ColorGradingTexture, _super);
  56329. /**
  56330. * Instantiates a ColorGradingTexture from the following parameters.
  56331. *
  56332. * @param url The location of the color gradind data (currently only supporting 3dl)
  56333. * @param scene The scene the texture will be used in
  56334. */
  56335. function ColorGradingTexture(url, scene) {
  56336. var _this = _super.call(this, scene) || this;
  56337. if (!url) {
  56338. return _this;
  56339. }
  56340. _this._textureMatrix = BABYLON.Matrix.Identity();
  56341. _this.name = url;
  56342. _this.url = url;
  56343. _this.hasAlpha = false;
  56344. _this.isCube = false;
  56345. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56346. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56347. _this.anisotropicFilteringLevel = 1;
  56348. _this._texture = _this._getFromCache(url, true);
  56349. if (!_this._texture) {
  56350. if (!scene.useDelayedTextureLoading) {
  56351. _this.loadTexture();
  56352. }
  56353. else {
  56354. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56355. }
  56356. }
  56357. return _this;
  56358. }
  56359. /**
  56360. * Returns the texture matrix used in most of the material.
  56361. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  56362. */
  56363. ColorGradingTexture.prototype.getTextureMatrix = function () {
  56364. return this._textureMatrix;
  56365. };
  56366. /**
  56367. * Occurs when the file being loaded is a .3dl LUT file.
  56368. */
  56369. ColorGradingTexture.prototype.load3dlTexture = function () {
  56370. var _this = this;
  56371. var mipLevels = 0;
  56372. var floatArrayView = null;
  56373. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56374. this._texture = texture;
  56375. var callback = function (text) {
  56376. var data;
  56377. var tempData;
  56378. var line;
  56379. var lines = text.split('\n');
  56380. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  56381. var maxColor = 0;
  56382. for (var i = 0; i < lines.length; i++) {
  56383. line = lines[i];
  56384. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  56385. continue;
  56386. if (line.indexOf('#') === 0)
  56387. continue;
  56388. var words = line.split(" ");
  56389. if (size === 0) {
  56390. // Number of space + one
  56391. size = words.length;
  56392. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  56393. tempData = new Float32Array(size * size * size * 4);
  56394. continue;
  56395. }
  56396. if (size != 0) {
  56397. var r = Math.max(parseInt(words[0]), 0);
  56398. var g = Math.max(parseInt(words[1]), 0);
  56399. var b = Math.max(parseInt(words[2]), 0);
  56400. maxColor = Math.max(r, maxColor);
  56401. maxColor = Math.max(g, maxColor);
  56402. maxColor = Math.max(b, maxColor);
  56403. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  56404. tempData[pixelStorageIndex + 0] = r;
  56405. tempData[pixelStorageIndex + 1] = g;
  56406. tempData[pixelStorageIndex + 2] = b;
  56407. tempData[pixelStorageIndex + 3] = 0;
  56408. pixelIndexSlice++;
  56409. if (pixelIndexSlice % size == 0) {
  56410. pixelIndexH++;
  56411. pixelIndexSlice = 0;
  56412. if (pixelIndexH % size == 0) {
  56413. pixelIndexW++;
  56414. pixelIndexH = 0;
  56415. }
  56416. }
  56417. }
  56418. }
  56419. for (var i = 0; i < tempData.length; i++) {
  56420. var value = tempData[i];
  56421. data[i] = (value / maxColor * 255);
  56422. }
  56423. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  56424. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  56425. };
  56426. BABYLON.Tools.LoadFile(this.url, callback);
  56427. return this._texture;
  56428. };
  56429. /**
  56430. * Starts the loading process of the texture.
  56431. */
  56432. ColorGradingTexture.prototype.loadTexture = function () {
  56433. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  56434. this.load3dlTexture();
  56435. }
  56436. };
  56437. /**
  56438. * Clones the color gradind texture.
  56439. */
  56440. ColorGradingTexture.prototype.clone = function () {
  56441. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  56442. // Base texture
  56443. newTexture.level = this.level;
  56444. return newTexture;
  56445. };
  56446. /**
  56447. * Called during delayed load for textures.
  56448. */
  56449. ColorGradingTexture.prototype.delayLoad = function () {
  56450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56451. return;
  56452. }
  56453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56454. this._texture = this._getFromCache(this.url, true);
  56455. if (!this._texture) {
  56456. this.loadTexture();
  56457. }
  56458. };
  56459. /**
  56460. * Binds the color grading to the shader.
  56461. * @param colorGrading The texture to bind
  56462. * @param effect The effect to bind to
  56463. */
  56464. ColorGradingTexture.Bind = function (colorGrading, effect) {
  56465. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  56466. var x = colorGrading.level; // Texture Level
  56467. var y = colorGrading.getSize().height; // Texture Size example with 8
  56468. var z = y - 1.0; // SizeMinusOne 8 - 1
  56469. var w = 1 / y; // Space of 1 slice 1 / 8
  56470. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  56471. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  56472. 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
  56473. 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
  56474. 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
  56475. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  56476. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  56477. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  56478. };
  56479. /**
  56480. * Prepare the list of uniforms associated with the ColorGrading effects.
  56481. * @param uniformsList The list of uniforms used in the effect
  56482. * @param samplersList The list of samplers used in the effect
  56483. */
  56484. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  56485. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  56486. samplersList.push("cameraColorGrading2DSampler");
  56487. };
  56488. /**
  56489. * Parses a color grading texture serialized by Babylon.
  56490. * @param parsedTexture The texture information being parsedTexture
  56491. * @param scene The scene to load the texture in
  56492. * @param rootUrl The root url of the data assets to load
  56493. * @return A color gradind texture
  56494. */
  56495. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56496. var texture = null;
  56497. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56498. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  56499. texture.name = parsedTexture.name;
  56500. texture.level = parsedTexture.level;
  56501. }
  56502. return texture;
  56503. };
  56504. /**
  56505. * Serializes the LUT texture to json format.
  56506. */
  56507. ColorGradingTexture.prototype.serialize = function () {
  56508. if (!this.name) {
  56509. return null;
  56510. }
  56511. var serializationObject = {};
  56512. serializationObject.name = this.name;
  56513. serializationObject.level = this.level;
  56514. serializationObject.customType = "BABYLON.ColorGradingTexture";
  56515. return serializationObject;
  56516. };
  56517. return ColorGradingTexture;
  56518. }(BABYLON.BaseTexture));
  56519. /**
  56520. * Empty line regex stored for GC.
  56521. */
  56522. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  56523. BABYLON.ColorGradingTexture = ColorGradingTexture;
  56524. })(BABYLON || (BABYLON = {}));
  56525. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  56526. var BABYLON;
  56527. (function (BABYLON) {
  56528. /**
  56529. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56530. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56531. * 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;
  56532. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56533. */
  56534. var ColorCurves = (function () {
  56535. function ColorCurves() {
  56536. this._dirty = true;
  56537. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  56538. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  56539. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56540. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  56541. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56542. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  56543. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  56544. this._globalHue = 30;
  56545. this._globalDensity = 0;
  56546. this._globalSaturation = 0;
  56547. this._globalExposure = 0;
  56548. this._highlightsHue = 30;
  56549. this._highlightsDensity = 0;
  56550. this._highlightsSaturation = 0;
  56551. this._highlightsExposure = 0;
  56552. this._midtonesHue = 30;
  56553. this._midtonesDensity = 0;
  56554. this._midtonesSaturation = 0;
  56555. this._midtonesExposure = 0;
  56556. this._shadowsHue = 30;
  56557. this._shadowsDensity = 0;
  56558. this._shadowsSaturation = 0;
  56559. this._shadowsExposure = 0;
  56560. }
  56561. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  56562. /**
  56563. * Gets the global Hue value.
  56564. * 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).
  56565. */
  56566. get: function () {
  56567. return this._globalHue;
  56568. },
  56569. /**
  56570. * Sets the global Hue value.
  56571. * 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).
  56572. */
  56573. set: function (value) {
  56574. this._globalHue = value;
  56575. this._dirty = true;
  56576. },
  56577. enumerable: true,
  56578. configurable: true
  56579. });
  56580. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  56581. /**
  56582. * Gets the global Density value.
  56583. * 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.
  56584. * Values less than zero provide a filter of opposite hue.
  56585. */
  56586. get: function () {
  56587. return this._globalDensity;
  56588. },
  56589. /**
  56590. * Sets the global Density value.
  56591. * 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.
  56592. * Values less than zero provide a filter of opposite hue.
  56593. */
  56594. set: function (value) {
  56595. this._globalDensity = value;
  56596. this._dirty = true;
  56597. },
  56598. enumerable: true,
  56599. configurable: true
  56600. });
  56601. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  56602. /**
  56603. * Gets the global Saturation value.
  56604. * 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.
  56605. */
  56606. get: function () {
  56607. return this._globalSaturation;
  56608. },
  56609. /**
  56610. * Sets the global Saturation value.
  56611. * 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.
  56612. */
  56613. set: function (value) {
  56614. this._globalSaturation = value;
  56615. this._dirty = true;
  56616. },
  56617. enumerable: true,
  56618. configurable: true
  56619. });
  56620. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  56621. /**
  56622. * Gets the highlights Hue value.
  56623. * 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).
  56624. */
  56625. get: function () {
  56626. return this._highlightsHue;
  56627. },
  56628. /**
  56629. * Sets the highlights Hue value.
  56630. * 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).
  56631. */
  56632. set: function (value) {
  56633. this._highlightsHue = value;
  56634. this._dirty = true;
  56635. },
  56636. enumerable: true,
  56637. configurable: true
  56638. });
  56639. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  56640. /**
  56641. * Gets the highlights Density value.
  56642. * 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.
  56643. * Values less than zero provide a filter of opposite hue.
  56644. */
  56645. get: function () {
  56646. return this._highlightsDensity;
  56647. },
  56648. /**
  56649. * Sets the highlights Density value.
  56650. * 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.
  56651. * Values less than zero provide a filter of opposite hue.
  56652. */
  56653. set: function (value) {
  56654. this._highlightsDensity = value;
  56655. this._dirty = true;
  56656. },
  56657. enumerable: true,
  56658. configurable: true
  56659. });
  56660. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  56661. /**
  56662. * Gets the highlights Saturation value.
  56663. * 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.
  56664. */
  56665. get: function () {
  56666. return this._highlightsSaturation;
  56667. },
  56668. /**
  56669. * Sets the highlights Saturation value.
  56670. * 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.
  56671. */
  56672. set: function (value) {
  56673. this._highlightsSaturation = value;
  56674. this._dirty = true;
  56675. },
  56676. enumerable: true,
  56677. configurable: true
  56678. });
  56679. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  56680. /**
  56681. * Gets the highlights Exposure value.
  56682. * 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.
  56683. */
  56684. get: function () {
  56685. return this._highlightsExposure;
  56686. },
  56687. /**
  56688. * Sets the highlights Exposure value.
  56689. * 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.
  56690. */
  56691. set: function (value) {
  56692. this._highlightsExposure = value;
  56693. this._dirty = true;
  56694. },
  56695. enumerable: true,
  56696. configurable: true
  56697. });
  56698. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  56699. /**
  56700. * Gets the midtones Hue value.
  56701. * 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).
  56702. */
  56703. get: function () {
  56704. return this._midtonesHue;
  56705. },
  56706. /**
  56707. * Sets the midtones Hue value.
  56708. * 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).
  56709. */
  56710. set: function (value) {
  56711. this._midtonesHue = value;
  56712. this._dirty = true;
  56713. },
  56714. enumerable: true,
  56715. configurable: true
  56716. });
  56717. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  56718. /**
  56719. * Gets the midtones Density value.
  56720. * 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.
  56721. * Values less than zero provide a filter of opposite hue.
  56722. */
  56723. get: function () {
  56724. return this._midtonesDensity;
  56725. },
  56726. /**
  56727. * Sets the midtones Density value.
  56728. * 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.
  56729. * Values less than zero provide a filter of opposite hue.
  56730. */
  56731. set: function (value) {
  56732. this._midtonesDensity = value;
  56733. this._dirty = true;
  56734. },
  56735. enumerable: true,
  56736. configurable: true
  56737. });
  56738. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  56739. /**
  56740. * Gets the midtones Saturation value.
  56741. * 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.
  56742. */
  56743. get: function () {
  56744. return this._midtonesSaturation;
  56745. },
  56746. /**
  56747. * Sets the midtones Saturation value.
  56748. * 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.
  56749. */
  56750. set: function (value) {
  56751. this._midtonesSaturation = value;
  56752. this._dirty = true;
  56753. },
  56754. enumerable: true,
  56755. configurable: true
  56756. });
  56757. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  56758. /**
  56759. * Gets the midtones Exposure value.
  56760. * 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.
  56761. */
  56762. get: function () {
  56763. return this._midtonesExposure;
  56764. },
  56765. /**
  56766. * Sets the midtones Exposure value.
  56767. * 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.
  56768. */
  56769. set: function (value) {
  56770. this._midtonesExposure = value;
  56771. this._dirty = true;
  56772. },
  56773. enumerable: true,
  56774. configurable: true
  56775. });
  56776. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  56777. /**
  56778. * Gets the shadows Hue value.
  56779. * 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).
  56780. */
  56781. get: function () {
  56782. return this._shadowsHue;
  56783. },
  56784. /**
  56785. * Sets the shadows Hue value.
  56786. * 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).
  56787. */
  56788. set: function (value) {
  56789. this._shadowsHue = value;
  56790. this._dirty = true;
  56791. },
  56792. enumerable: true,
  56793. configurable: true
  56794. });
  56795. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  56796. /**
  56797. * Gets the shadows Density value.
  56798. * 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.
  56799. * Values less than zero provide a filter of opposite hue.
  56800. */
  56801. get: function () {
  56802. return this._shadowsDensity;
  56803. },
  56804. /**
  56805. * Sets the shadows Density value.
  56806. * 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.
  56807. * Values less than zero provide a filter of opposite hue.
  56808. */
  56809. set: function (value) {
  56810. this._shadowsDensity = value;
  56811. this._dirty = true;
  56812. },
  56813. enumerable: true,
  56814. configurable: true
  56815. });
  56816. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  56817. /**
  56818. * Gets the shadows Saturation value.
  56819. * 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.
  56820. */
  56821. get: function () {
  56822. return this._shadowsSaturation;
  56823. },
  56824. /**
  56825. * Sets the shadows Saturation value.
  56826. * 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.
  56827. */
  56828. set: function (value) {
  56829. this._shadowsSaturation = value;
  56830. this._dirty = true;
  56831. },
  56832. enumerable: true,
  56833. configurable: true
  56834. });
  56835. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  56836. /**
  56837. * Gets the shadows Exposure value.
  56838. * 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.
  56839. */
  56840. get: function () {
  56841. return this._shadowsExposure;
  56842. },
  56843. /**
  56844. * Sets the shadows Exposure value.
  56845. * 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.
  56846. */
  56847. set: function (value) {
  56848. this._shadowsExposure = value;
  56849. this._dirty = true;
  56850. },
  56851. enumerable: true,
  56852. configurable: true
  56853. });
  56854. /**
  56855. * Binds the color curves to the shader.
  56856. * @param colorCurves The color curve to bind
  56857. * @param effect The effect to bind to
  56858. */
  56859. ColorCurves.Bind = function (colorCurves, effect) {
  56860. if (colorCurves._dirty) {
  56861. colorCurves._dirty = false;
  56862. // Fill in global info.
  56863. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  56864. // Compute highlights info.
  56865. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  56866. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  56867. // Compute midtones info.
  56868. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  56869. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  56870. // Compute shadows info.
  56871. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  56872. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  56873. // Compute deltas (neutral is midtones).
  56874. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  56875. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  56876. }
  56877. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  56878. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  56879. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  56880. };
  56881. /**
  56882. * Prepare the list of uniforms associated with the ColorCurves effects.
  56883. * @param uniformsList The list of uniforms used in the effect
  56884. */
  56885. ColorCurves.PrepareUniforms = function (uniformsList) {
  56886. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  56887. };
  56888. /**
  56889. * Returns color grading data based on a hue, density, saturation and exposure value.
  56890. * @param filterHue The hue of the color filter.
  56891. * @param filterDensity The density of the color filter.
  56892. * @param saturation The saturation.
  56893. * @param exposure The exposure.
  56894. * @param result The result data container.
  56895. */
  56896. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  56897. if (hue == null) {
  56898. return;
  56899. }
  56900. hue = ColorCurves.clamp(hue, 0, 360);
  56901. density = ColorCurves.clamp(density, -100, 100);
  56902. saturation = ColorCurves.clamp(saturation, -100, 100);
  56903. exposure = ColorCurves.clamp(exposure, -100, 100);
  56904. // Remap the slider/config filter density with non-linear mapping and also scale by half
  56905. // so that the maximum filter density is only 50% control. This provides fine control
  56906. // for small values and reasonable range.
  56907. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  56908. density *= 0.5;
  56909. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  56910. if (density < 0) {
  56911. density *= -1;
  56912. hue = (hue + 180) % 360;
  56913. }
  56914. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  56915. result.scaleToRef(2, result);
  56916. result.a = 1 + 0.01 * saturation;
  56917. };
  56918. /**
  56919. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  56920. * @param value The input slider value in range [-100,100].
  56921. * @returns Adjusted value.
  56922. */
  56923. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  56924. value /= 100;
  56925. var x = Math.abs(value);
  56926. x = Math.pow(x, 2);
  56927. if (value < 0) {
  56928. x *= -1;
  56929. }
  56930. x *= 100;
  56931. return x;
  56932. };
  56933. /**
  56934. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  56935. * @param hue The hue (H) input.
  56936. * @param saturation The saturation (S) input.
  56937. * @param brightness The brightness (B) input.
  56938. * @result An RGBA color represented as Vector4.
  56939. */
  56940. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  56941. var h = ColorCurves.clamp(hue, 0, 360);
  56942. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  56943. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  56944. if (s === 0) {
  56945. result.r = v;
  56946. result.g = v;
  56947. result.b = v;
  56948. }
  56949. else {
  56950. // sector 0 to 5
  56951. h /= 60;
  56952. var i = Math.floor(h);
  56953. // fractional part of h
  56954. var f = h - i;
  56955. var p = v * (1 - s);
  56956. var q = v * (1 - s * f);
  56957. var t = v * (1 - s * (1 - f));
  56958. switch (i) {
  56959. case 0:
  56960. result.r = v;
  56961. result.g = t;
  56962. result.b = p;
  56963. break;
  56964. case 1:
  56965. result.r = q;
  56966. result.g = v;
  56967. result.b = p;
  56968. break;
  56969. case 2:
  56970. result.r = p;
  56971. result.g = v;
  56972. result.b = t;
  56973. break;
  56974. case 3:
  56975. result.r = p;
  56976. result.g = q;
  56977. result.b = v;
  56978. break;
  56979. case 4:
  56980. result.r = t;
  56981. result.g = p;
  56982. result.b = v;
  56983. break;
  56984. default:
  56985. result.r = v;
  56986. result.g = p;
  56987. result.b = q;
  56988. break;
  56989. }
  56990. }
  56991. result.a = 1;
  56992. };
  56993. /**
  56994. * Returns a value clamped between min and max
  56995. * @param value The value to clamp
  56996. * @param min The minimum of value
  56997. * @param max The maximum of value
  56998. * @returns The clamped value.
  56999. */
  57000. ColorCurves.clamp = function (value, min, max) {
  57001. return Math.min(Math.max(value, min), max);
  57002. };
  57003. /**
  57004. * Clones the current color curve instance.
  57005. * @return The cloned curves
  57006. */
  57007. ColorCurves.prototype.clone = function () {
  57008. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57009. };
  57010. /**
  57011. * Serializes the current color curve instance to a json representation.
  57012. * @return a JSON representation
  57013. */
  57014. ColorCurves.prototype.serialize = function () {
  57015. return BABYLON.SerializationHelper.Serialize(this);
  57016. };
  57017. /**
  57018. * Parses the color curve from a json representation.
  57019. * @param source the JSON source to parse
  57020. * @return The parsed curves
  57021. */
  57022. ColorCurves.Parse = function (source) {
  57023. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57024. };
  57025. return ColorCurves;
  57026. }());
  57027. __decorate([
  57028. BABYLON.serialize()
  57029. ], ColorCurves.prototype, "_globalHue", void 0);
  57030. __decorate([
  57031. BABYLON.serialize()
  57032. ], ColorCurves.prototype, "_globalDensity", void 0);
  57033. __decorate([
  57034. BABYLON.serialize()
  57035. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57036. __decorate([
  57037. BABYLON.serialize()
  57038. ], ColorCurves.prototype, "_globalExposure", void 0);
  57039. __decorate([
  57040. BABYLON.serialize()
  57041. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57042. __decorate([
  57043. BABYLON.serialize()
  57044. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57045. __decorate([
  57046. BABYLON.serialize()
  57047. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57048. __decorate([
  57049. BABYLON.serialize()
  57050. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57051. __decorate([
  57052. BABYLON.serialize()
  57053. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57054. __decorate([
  57055. BABYLON.serialize()
  57056. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57057. __decorate([
  57058. BABYLON.serialize()
  57059. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57060. __decorate([
  57061. BABYLON.serialize()
  57062. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57063. BABYLON.ColorCurves = ColorCurves;
  57064. })(BABYLON || (BABYLON = {}));
  57065. //# sourceMappingURL=babylon.colorCurves.js.map
  57066. var BABYLON;
  57067. (function (BABYLON) {
  57068. var PBRMaterialDefines = (function (_super) {
  57069. __extends(PBRMaterialDefines, _super);
  57070. function PBRMaterialDefines() {
  57071. var _this = _super.call(this) || this;
  57072. _this.ALBEDO = false;
  57073. _this.AMBIENT = false;
  57074. _this.OPACITY = false;
  57075. _this.OPACITYRGB = false;
  57076. _this.REFLECTION = false;
  57077. _this.EMISSIVE = false;
  57078. _this.REFLECTIVITY = false;
  57079. _this.BUMP = false;
  57080. _this.PARALLAX = false;
  57081. _this.PARALLAXOCCLUSION = false;
  57082. _this.SPECULAROVERALPHA = false;
  57083. _this.CLIPPLANE = false;
  57084. _this.ALPHATEST = false;
  57085. _this.ALPHAFROMALBEDO = false;
  57086. _this.POINTSIZE = false;
  57087. _this.FOG = false;
  57088. _this.SPECULARTERM = false;
  57089. _this.OPACITYFRESNEL = false;
  57090. _this.EMISSIVEFRESNEL = false;
  57091. _this.FRESNEL = false;
  57092. _this.NORMAL = false;
  57093. _this.UV1 = false;
  57094. _this.UV2 = false;
  57095. _this.VERTEXCOLOR = false;
  57096. _this.VERTEXALPHA = false;
  57097. _this.NUM_BONE_INFLUENCERS = 0;
  57098. _this.BonesPerMesh = 0;
  57099. _this.INSTANCES = false;
  57100. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  57101. _this.MICROSURFACEAUTOMATIC = false;
  57102. _this.EMISSIVEASILLUMINATION = false;
  57103. _this.LINKEMISSIVEWITHALBEDO = false;
  57104. _this.LIGHTMAP = false;
  57105. _this.USELIGHTMAPASSHADOWMAP = false;
  57106. _this.REFLECTIONMAP_3D = false;
  57107. _this.REFLECTIONMAP_SPHERICAL = false;
  57108. _this.REFLECTIONMAP_PLANAR = false;
  57109. _this.REFLECTIONMAP_CUBIC = false;
  57110. _this.REFLECTIONMAP_PROJECTION = false;
  57111. _this.REFLECTIONMAP_SKYBOX = false;
  57112. _this.REFLECTIONMAP_EXPLICIT = false;
  57113. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  57114. _this.INVERTCUBICMAP = false;
  57115. _this.LOGARITHMICDEPTH = false;
  57116. _this.CAMERATONEMAP = false;
  57117. _this.CAMERACONTRAST = false;
  57118. _this.CAMERACOLORGRADING = false;
  57119. _this.CAMERACOLORCURVES = false;
  57120. _this.OVERLOADEDVALUES = false;
  57121. _this.OVERLOADEDSHADOWVALUES = false;
  57122. _this.USESPHERICALFROMREFLECTIONMAP = false;
  57123. _this.REFRACTION = false;
  57124. _this.REFRACTIONMAP_3D = false;
  57125. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  57126. _this.REFRACTIONMAPINLINEARSPACE = false;
  57127. _this.LODBASEDMICROSFURACE = false;
  57128. _this.USEPHYSICALLIGHTFALLOFF = false;
  57129. _this.RADIANCEOVERALPHA = false;
  57130. _this.USEPMREMREFLECTION = false;
  57131. _this.USEPMREMREFRACTION = false;
  57132. _this.OPENGLNORMALMAP = false;
  57133. _this.INVERTNORMALMAPX = false;
  57134. _this.INVERTNORMALMAPY = false;
  57135. _this.SHADOWFULLFLOAT = false;
  57136. _this.METALLICWORKFLOW = false;
  57137. _this.METALLICROUGHNESSMAP = false;
  57138. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  57139. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  57140. _this.rebuild();
  57141. return _this;
  57142. }
  57143. return PBRMaterialDefines;
  57144. }(BABYLON.MaterialDefines));
  57145. /**
  57146. * The Physically based material of BJS.
  57147. *
  57148. * This offers the main features of a standard PBR material.
  57149. * For more information, please refer to the documentation :
  57150. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  57151. */
  57152. var PBRMaterial = (function (_super) {
  57153. __extends(PBRMaterial, _super);
  57154. /**
  57155. * Instantiates a new PBRMaterial instance.
  57156. *
  57157. * @param name The material name
  57158. * @param scene The scene the material will be use in.
  57159. */
  57160. function PBRMaterial(name, scene) {
  57161. var _this = _super.call(this, name, scene) || this;
  57162. /**
  57163. * Intensity of the direct lights e.g. the four lights available in your scene.
  57164. * This impacts both the direct diffuse and specular highlights.
  57165. */
  57166. _this.directIntensity = 1.0;
  57167. /**
  57168. * Intensity of the emissive part of the material.
  57169. * This helps controlling the emissive effect without modifying the emissive color.
  57170. */
  57171. _this.emissiveIntensity = 1.0;
  57172. /**
  57173. * Intensity of the environment e.g. how much the environment will light the object
  57174. * either through harmonics for rough material or through the refelction for shiny ones.
  57175. */
  57176. _this.environmentIntensity = 1.0;
  57177. /**
  57178. * This is a special control allowing the reduction of the specular highlights coming from the
  57179. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  57180. */
  57181. _this.specularIntensity = 1.0;
  57182. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  57183. /**
  57184. * Debug Control allowing disabling the bump map on this material.
  57185. */
  57186. _this.disableBumpMap = false;
  57187. /**
  57188. * Debug Control helping enforcing or dropping the darkness of shadows.
  57189. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  57190. */
  57191. _this.overloadedShadowIntensity = 1.0;
  57192. /**
  57193. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  57194. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  57195. */
  57196. _this.overloadedShadeIntensity = 1.0;
  57197. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  57198. /**
  57199. * The camera exposure used on this material.
  57200. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  57201. * This corresponds to a photographic exposure.
  57202. */
  57203. _this.cameraExposure = 1.0;
  57204. /**
  57205. * The camera contrast used on this material.
  57206. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  57207. */
  57208. _this.cameraContrast = 1.0;
  57209. /**
  57210. * Color Grading 2D Lookup Texture.
  57211. * This allows special effects like sepia, black and white to sixties rendering style.
  57212. */
  57213. _this.cameraColorGradingTexture = null;
  57214. /**
  57215. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57216. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57217. * 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;
  57218. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57219. */
  57220. _this.cameraColorCurves = null;
  57221. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  57222. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  57223. /**
  57224. * Debug Control allowing to overload the ambient color.
  57225. * This as to be use with the overloadedAmbientIntensity parameter.
  57226. */
  57227. _this.overloadedAmbient = BABYLON.Color3.White();
  57228. /**
  57229. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  57230. */
  57231. _this.overloadedAmbientIntensity = 0.0;
  57232. /**
  57233. * Debug Control allowing to overload the albedo color.
  57234. * This as to be use with the overloadedAlbedoIntensity parameter.
  57235. */
  57236. _this.overloadedAlbedo = BABYLON.Color3.White();
  57237. /**
  57238. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  57239. */
  57240. _this.overloadedAlbedoIntensity = 0.0;
  57241. /**
  57242. * Debug Control allowing to overload the reflectivity color.
  57243. * This as to be use with the overloadedReflectivityIntensity parameter.
  57244. */
  57245. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  57246. /**
  57247. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  57248. */
  57249. _this.overloadedReflectivityIntensity = 0.0;
  57250. /**
  57251. * Debug Control allowing to overload the emissive color.
  57252. * This as to be use with the overloadedEmissiveIntensity parameter.
  57253. */
  57254. _this.overloadedEmissive = BABYLON.Color3.White();
  57255. /**
  57256. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  57257. */
  57258. _this.overloadedEmissiveIntensity = 0.0;
  57259. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  57260. /**
  57261. * Debug Control allowing to overload the reflection color.
  57262. * This as to be use with the overloadedReflectionIntensity parameter.
  57263. */
  57264. _this.overloadedReflection = BABYLON.Color3.White();
  57265. /**
  57266. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  57267. */
  57268. _this.overloadedReflectionIntensity = 0.0;
  57269. /**
  57270. * Debug Control allowing to overload the microsurface.
  57271. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  57272. */
  57273. _this.overloadedMicroSurface = 0.0;
  57274. /**
  57275. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  57276. */
  57277. _this.overloadedMicroSurfaceIntensity = 0.0;
  57278. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  57279. /**
  57280. * AKA Occlusion Texture Intensity in other nomenclature.
  57281. */
  57282. _this.ambientTextureStrength = 1.0;
  57283. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  57284. /**
  57285. * AKA Diffuse Color in other nomenclature.
  57286. */
  57287. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  57288. /**
  57289. * AKA Specular Color in other nomenclature.
  57290. */
  57291. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  57292. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  57293. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  57294. /**
  57295. * AKA Glossiness in other nomenclature.
  57296. */
  57297. _this.microSurface = 0.9;
  57298. /**
  57299. * source material index of refraction (IOR)' / 'destination material IOR.
  57300. */
  57301. _this.indexOfRefraction = 0.66;
  57302. /**
  57303. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  57304. */
  57305. _this.invertRefractionY = false;
  57306. /**
  57307. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  57308. * Materials half opaque for instance using refraction could benefit from this control.
  57309. */
  57310. _this.linkRefractionWithTransparency = false;
  57311. /**
  57312. * The emissive and albedo are linked to never be more than one (Energy conservation).
  57313. */
  57314. _this.linkEmissiveWithAlbedo = false;
  57315. _this.useLightmapAsShadowmap = false;
  57316. /**
  57317. * In this mode, the emissive informtaion will always be added to the lighting once.
  57318. * A light for instance can be thought as emissive.
  57319. */
  57320. _this.useEmissiveAsIllumination = false;
  57321. /**
  57322. * Secifies that the alpha is coming form the albedo channel alpha channel.
  57323. */
  57324. _this.useAlphaFromAlbedoTexture = false;
  57325. /**
  57326. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  57327. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  57328. */
  57329. _this.useSpecularOverAlpha = true;
  57330. /**
  57331. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  57332. */
  57333. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  57334. /**
  57335. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  57336. */
  57337. _this.useRoughnessFromMetallicTextureAlpha = true;
  57338. /**
  57339. * Specifies if the metallic texture contains the roughness information in its green channel.
  57340. */
  57341. _this.useRoughnessFromMetallicTextureGreen = false;
  57342. /**
  57343. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  57344. * The material will try to infer what glossiness each pixel should be.
  57345. */
  57346. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  57347. /**
  57348. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  57349. * the creation of the material.
  57350. */
  57351. _this.useScalarInLinearSpace = false;
  57352. /**
  57353. * BJS is using an harcoded light falloff based on a manually sets up range.
  57354. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  57355. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  57356. */
  57357. _this.usePhysicalLightFalloff = true;
  57358. /**
  57359. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  57360. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  57361. */
  57362. _this.useRadianceOverAlpha = true;
  57363. /**
  57364. * Allows using the bump map in parallax mode.
  57365. */
  57366. _this.useParallax = false;
  57367. /**
  57368. * Allows using the bump map in parallax occlusion mode.
  57369. */
  57370. _this.useParallaxOcclusion = false;
  57371. /**
  57372. * Controls the scale bias of the parallax mode.
  57373. */
  57374. _this.parallaxScaleBias = 0.05;
  57375. /**
  57376. * If sets to true, disables all the lights affecting the material.
  57377. */
  57378. _this.disableLighting = false;
  57379. /**
  57380. * Number of Simultaneous lights allowed on the material.
  57381. */
  57382. _this.maxSimultaneousLights = 4;
  57383. /**
  57384. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  57385. */
  57386. _this.invertNormalMapX = false;
  57387. /**
  57388. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  57389. */
  57390. _this.invertNormalMapY = false;
  57391. _this._renderTargets = new BABYLON.SmartArray(16);
  57392. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  57393. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  57394. _this._tempColor = new BABYLON.Color3();
  57395. _this._defines = new PBRMaterialDefines();
  57396. _this._cachedDefines = new PBRMaterialDefines();
  57397. _this._myScene = null;
  57398. _this._myShadowGenerator = null;
  57399. _this._cachedDefines.BonesPerMesh = -1;
  57400. _this.getRenderTargetTextures = function () {
  57401. _this._renderTargets.reset();
  57402. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  57403. _this._renderTargets.push(_this.reflectionTexture);
  57404. }
  57405. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  57406. _this._renderTargets.push(_this.refractionTexture);
  57407. }
  57408. return _this._renderTargets;
  57409. };
  57410. return _this;
  57411. }
  57412. PBRMaterial.prototype.getClassName = function () {
  57413. return "PBRMaterial";
  57414. };
  57415. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  57416. get: function () {
  57417. return this._useLogarithmicDepth;
  57418. },
  57419. set: function (value) {
  57420. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. PBRMaterial.prototype.needAlphaBlending = function () {
  57426. if (this.linkRefractionWithTransparency) {
  57427. return false;
  57428. }
  57429. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  57430. };
  57431. PBRMaterial.prototype.needAlphaTesting = function () {
  57432. if (this.linkRefractionWithTransparency) {
  57433. return false;
  57434. }
  57435. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  57436. };
  57437. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  57438. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  57439. };
  57440. PBRMaterial.prototype.getAlphaTestTexture = function () {
  57441. return this.albedoTexture;
  57442. };
  57443. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57444. if (!mesh) {
  57445. return true;
  57446. }
  57447. if (this._defines.INSTANCES !== useInstances) {
  57448. return false;
  57449. }
  57450. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  57451. return true;
  57452. }
  57453. return false;
  57454. };
  57455. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  57456. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  57457. };
  57458. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  57459. if (!useScalarInLinear) {
  57460. color.toLinearSpaceToRef(ref);
  57461. }
  57462. else {
  57463. ref.r = color.r;
  57464. ref.g = color.g;
  57465. ref.b = color.b;
  57466. }
  57467. };
  57468. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  57469. var lightIndex = 0;
  57470. var depthValuesAlreadySet = false;
  57471. for (var index = 0; index < scene.lights.length; index++) {
  57472. var light = scene.lights[index];
  57473. if (!light.isEnabled()) {
  57474. continue;
  57475. }
  57476. if (!light.canAffectMesh(mesh)) {
  57477. continue;
  57478. }
  57479. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  57480. // GAMMA CORRECTION.
  57481. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  57482. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  57483. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  57484. if (defines["SPECULARTERM"]) {
  57485. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  57486. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  57487. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  57488. }
  57489. // Shadows
  57490. if (scene.shadowsEnabled) {
  57491. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  57492. }
  57493. lightIndex++;
  57494. if (lightIndex === maxSimultaneousLights)
  57495. break;
  57496. }
  57497. };
  57498. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  57499. if (this.isFrozen) {
  57500. if (this._wasPreviouslyReady) {
  57501. return true;
  57502. }
  57503. }
  57504. var scene = this.getScene();
  57505. var engine = scene.getEngine();
  57506. var needNormals = false;
  57507. var needUVs = false;
  57508. this._defines.reset();
  57509. if (scene.lightsEnabled && !this.disableLighting) {
  57510. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  57511. }
  57512. if (!this.checkReadyOnEveryCall) {
  57513. if (this._renderId === scene.getRenderId()) {
  57514. if (this._checkCache(scene, mesh, useInstances)) {
  57515. return true;
  57516. }
  57517. }
  57518. }
  57519. if (scene.texturesEnabled) {
  57520. if (scene.getEngine().getCaps().textureLOD) {
  57521. this._defines.LODBASEDMICROSFURACE = true;
  57522. }
  57523. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  57524. if (!this.albedoTexture.isReady()) {
  57525. return false;
  57526. }
  57527. else {
  57528. needUVs = true;
  57529. this._defines.ALBEDO = true;
  57530. }
  57531. }
  57532. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  57533. if (!this.ambientTexture.isReady()) {
  57534. return false;
  57535. }
  57536. else {
  57537. needUVs = true;
  57538. this._defines.AMBIENT = true;
  57539. }
  57540. }
  57541. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  57542. if (!this.opacityTexture.isReady()) {
  57543. return false;
  57544. }
  57545. else {
  57546. needUVs = true;
  57547. this._defines.OPACITY = true;
  57548. if (this.opacityTexture.getAlphaFromRGB) {
  57549. this._defines.OPACITYRGB = true;
  57550. }
  57551. }
  57552. }
  57553. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  57554. if (!this.reflectionTexture.isReady()) {
  57555. return false;
  57556. }
  57557. else {
  57558. needNormals = true;
  57559. this._defines.REFLECTION = true;
  57560. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  57561. this._defines.INVERTCUBICMAP = true;
  57562. }
  57563. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  57564. switch (this.reflectionTexture.coordinatesMode) {
  57565. case BABYLON.Texture.CUBIC_MODE:
  57566. case BABYLON.Texture.INVCUBIC_MODE:
  57567. this._defines.REFLECTIONMAP_CUBIC = true;
  57568. break;
  57569. case BABYLON.Texture.EXPLICIT_MODE:
  57570. this._defines.REFLECTIONMAP_EXPLICIT = true;
  57571. break;
  57572. case BABYLON.Texture.PLANAR_MODE:
  57573. this._defines.REFLECTIONMAP_PLANAR = true;
  57574. break;
  57575. case BABYLON.Texture.PROJECTION_MODE:
  57576. this._defines.REFLECTIONMAP_PROJECTION = true;
  57577. break;
  57578. case BABYLON.Texture.SKYBOX_MODE:
  57579. this._defines.REFLECTIONMAP_SKYBOX = true;
  57580. break;
  57581. case BABYLON.Texture.SPHERICAL_MODE:
  57582. this._defines.REFLECTIONMAP_SPHERICAL = true;
  57583. break;
  57584. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  57585. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  57586. break;
  57587. }
  57588. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  57589. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  57590. needNormals = true;
  57591. if (this.reflectionTexture.isPMREM) {
  57592. this._defines.USEPMREMREFLECTION = true;
  57593. }
  57594. }
  57595. }
  57596. }
  57597. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  57598. if (!this.lightmapTexture.isReady()) {
  57599. return false;
  57600. }
  57601. else {
  57602. needUVs = true;
  57603. this._defines.LIGHTMAP = true;
  57604. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  57605. }
  57606. }
  57607. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  57608. if (!this.emissiveTexture.isReady()) {
  57609. return false;
  57610. }
  57611. else {
  57612. needUVs = true;
  57613. this._defines.EMISSIVE = true;
  57614. }
  57615. }
  57616. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  57617. if (this.metallicTexture) {
  57618. if (!this.metallicTexture.isReady()) {
  57619. return false;
  57620. }
  57621. else {
  57622. needUVs = true;
  57623. this._defines.METALLICWORKFLOW = true;
  57624. this._defines.METALLICROUGHNESSMAP = true;
  57625. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  57626. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  57627. }
  57628. }
  57629. else if (this.reflectivityTexture) {
  57630. if (!this.reflectivityTexture.isReady()) {
  57631. return false;
  57632. }
  57633. else {
  57634. needUVs = true;
  57635. this._defines.REFLECTIVITY = true;
  57636. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  57637. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  57638. }
  57639. }
  57640. }
  57641. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  57642. if (!this.bumpTexture.isReady()) {
  57643. return false;
  57644. }
  57645. else {
  57646. needUVs = true;
  57647. this._defines.BUMP = true;
  57648. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  57649. this._defines.PARALLAX = true;
  57650. if (this.useParallaxOcclusion) {
  57651. this._defines.PARALLAXOCCLUSION = true;
  57652. }
  57653. }
  57654. if (this.invertNormalMapX) {
  57655. this._defines.INVERTNORMALMAPX = true;
  57656. }
  57657. if (this.invertNormalMapY) {
  57658. this._defines.INVERTNORMALMAPY = true;
  57659. }
  57660. if (scene._mirroredCameraPosition) {
  57661. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  57662. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  57663. }
  57664. }
  57665. }
  57666. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  57667. if (!this.refractionTexture.isReady()) {
  57668. return false;
  57669. }
  57670. else {
  57671. needUVs = true;
  57672. this._defines.REFRACTION = true;
  57673. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  57674. if (this.linkRefractionWithTransparency) {
  57675. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  57676. }
  57677. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  57678. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  57679. if (this.refractionTexture.isPMREM) {
  57680. this._defines.USEPMREMREFRACTION = true;
  57681. }
  57682. }
  57683. }
  57684. }
  57685. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  57686. if (!this.cameraColorGradingTexture.isReady()) {
  57687. return false;
  57688. }
  57689. else {
  57690. this._defines.CAMERACOLORGRADING = true;
  57691. }
  57692. }
  57693. }
  57694. // Effect
  57695. if (scene.clipPlane) {
  57696. this._defines.CLIPPLANE = true;
  57697. }
  57698. if (engine.getAlphaTesting()) {
  57699. this._defines.ALPHATEST = true;
  57700. }
  57701. if (this._shouldUseAlphaFromAlbedoTexture()) {
  57702. this._defines.ALPHAFROMALBEDO = true;
  57703. }
  57704. if (this.useEmissiveAsIllumination) {
  57705. this._defines.EMISSIVEASILLUMINATION = true;
  57706. }
  57707. if (this.linkEmissiveWithAlbedo) {
  57708. this._defines.LINKEMISSIVEWITHALBEDO = true;
  57709. }
  57710. if (this.useLogarithmicDepth) {
  57711. this._defines.LOGARITHMICDEPTH = true;
  57712. }
  57713. if (this.cameraContrast != 1) {
  57714. this._defines.CAMERACONTRAST = true;
  57715. }
  57716. if (this.cameraExposure != 1) {
  57717. this._defines.CAMERATONEMAP = true;
  57718. }
  57719. if (this.cameraColorCurves) {
  57720. this._defines.CAMERACOLORCURVES = true;
  57721. }
  57722. if (this.overloadedShadeIntensity != 1 ||
  57723. this.overloadedShadowIntensity != 1) {
  57724. this._defines.OVERLOADEDSHADOWVALUES = true;
  57725. }
  57726. if (this.overloadedMicroSurfaceIntensity > 0 ||
  57727. this.overloadedEmissiveIntensity > 0 ||
  57728. this.overloadedReflectivityIntensity > 0 ||
  57729. this.overloadedAlbedoIntensity > 0 ||
  57730. this.overloadedAmbientIntensity > 0 ||
  57731. this.overloadedReflectionIntensity > 0) {
  57732. this._defines.OVERLOADEDVALUES = true;
  57733. }
  57734. // Point size
  57735. if (this.pointsCloud || scene.forcePointsCloud) {
  57736. this._defines.POINTSIZE = true;
  57737. }
  57738. // Fog
  57739. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  57740. this._defines.FOG = true;
  57741. }
  57742. if (BABYLON.StandardMaterial.FresnelEnabled) {
  57743. // Fresnel
  57744. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  57745. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57746. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  57747. this._defines.OPACITYFRESNEL = true;
  57748. }
  57749. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57750. this._defines.EMISSIVEFRESNEL = true;
  57751. }
  57752. needNormals = true;
  57753. this._defines.FRESNEL = true;
  57754. }
  57755. }
  57756. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  57757. this._defines.SPECULAROVERALPHA = true;
  57758. }
  57759. if (this.usePhysicalLightFalloff) {
  57760. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  57761. }
  57762. if (this.useRadianceOverAlpha) {
  57763. this._defines.RADIANCEOVERALPHA = true;
  57764. }
  57765. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  57766. this._defines.METALLICWORKFLOW = true;
  57767. }
  57768. // Attribs
  57769. if (mesh) {
  57770. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  57771. this._defines.NORMAL = true;
  57772. }
  57773. if (needUVs) {
  57774. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57775. this._defines.UV1 = true;
  57776. }
  57777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57778. this._defines.UV2 = true;
  57779. }
  57780. }
  57781. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57782. this._defines.VERTEXCOLOR = true;
  57783. if (mesh.hasVertexAlpha) {
  57784. this._defines.VERTEXALPHA = true;
  57785. }
  57786. }
  57787. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57788. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  57789. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  57790. }
  57791. // Instances
  57792. if (useInstances) {
  57793. this._defines.INSTANCES = true;
  57794. }
  57795. }
  57796. // Get correct effect
  57797. if (!this._defines.isEqual(this._cachedDefines)) {
  57798. this._defines.cloneTo(this._cachedDefines);
  57799. scene.resetCachedMaterial();
  57800. // Fallbacks
  57801. var fallbacks = new BABYLON.EffectFallbacks();
  57802. if (this._defines.REFLECTION) {
  57803. fallbacks.addFallback(0, "REFLECTION");
  57804. }
  57805. if (this._defines.REFRACTION) {
  57806. fallbacks.addFallback(0, "REFRACTION");
  57807. }
  57808. if (this._defines.REFLECTIVITY) {
  57809. fallbacks.addFallback(0, "REFLECTIVITY");
  57810. }
  57811. if (this._defines.BUMP) {
  57812. fallbacks.addFallback(0, "BUMP");
  57813. }
  57814. if (this._defines.PARALLAX) {
  57815. fallbacks.addFallback(1, "PARALLAX");
  57816. }
  57817. if (this._defines.PARALLAXOCCLUSION) {
  57818. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  57819. }
  57820. if (this._defines.SPECULAROVERALPHA) {
  57821. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  57822. }
  57823. if (this._defines.FOG) {
  57824. fallbacks.addFallback(1, "FOG");
  57825. }
  57826. if (this._defines.POINTSIZE) {
  57827. fallbacks.addFallback(0, "POINTSIZE");
  57828. }
  57829. if (this._defines.LOGARITHMICDEPTH) {
  57830. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  57831. }
  57832. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  57833. if (this._defines.SPECULARTERM) {
  57834. fallbacks.addFallback(0, "SPECULARTERM");
  57835. }
  57836. if (this._defines.OPACITYFRESNEL) {
  57837. fallbacks.addFallback(1, "OPACITYFRESNEL");
  57838. }
  57839. if (this._defines.EMISSIVEFRESNEL) {
  57840. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  57841. }
  57842. if (this._defines.FRESNEL) {
  57843. fallbacks.addFallback(3, "FRESNEL");
  57844. }
  57845. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  57846. fallbacks.addCPUSkinningFallback(0, mesh);
  57847. }
  57848. //Attributes
  57849. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57850. if (this._defines.NORMAL) {
  57851. attribs.push(BABYLON.VertexBuffer.NormalKind);
  57852. }
  57853. if (this._defines.UV1) {
  57854. attribs.push(BABYLON.VertexBuffer.UVKind);
  57855. }
  57856. if (this._defines.UV2) {
  57857. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57858. }
  57859. if (this._defines.VERTEXCOLOR) {
  57860. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57861. }
  57862. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  57863. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  57864. // Legacy browser patch
  57865. var join = this._defines.toString();
  57866. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  57867. "vFogInfos", "vFogColor", "pointSize",
  57868. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  57869. "mBones",
  57870. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  57871. "depthValues",
  57872. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  57873. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  57874. "logarithmicDepthConstant",
  57875. "vSphericalX", "vSphericalY", "vSphericalZ",
  57876. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  57877. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  57878. "vMicrosurfaceTextureLods",
  57879. "vCameraInfos"
  57880. ];
  57881. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  57882. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  57883. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  57884. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  57885. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  57886. }
  57887. if (!this._effect.isReady()) {
  57888. return false;
  57889. }
  57890. this._renderId = scene.getRenderId();
  57891. this._wasPreviouslyReady = true;
  57892. if (mesh) {
  57893. if (!mesh._materialDefines) {
  57894. mesh._materialDefines = new PBRMaterialDefines();
  57895. }
  57896. this._defines.cloneTo(mesh._materialDefines);
  57897. }
  57898. return true;
  57899. };
  57900. PBRMaterial.prototype.unbind = function () {
  57901. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  57902. this._effect.setTexture("reflection2DSampler", null);
  57903. }
  57904. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  57905. this._effect.setTexture("refraction2DSampler", null);
  57906. }
  57907. _super.prototype.unbind.call(this);
  57908. };
  57909. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57910. this._effect.setMatrix("world", world);
  57911. };
  57912. PBRMaterial.prototype.bind = function (world, mesh) {
  57913. this._myScene = this.getScene();
  57914. // Matrices
  57915. this.bindOnlyWorldMatrix(world);
  57916. // Bones
  57917. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57918. if (this._myScene.getCachedMaterial() !== this) {
  57919. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  57920. if (BABYLON.StandardMaterial.FresnelEnabled) {
  57921. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  57922. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  57923. }
  57924. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  57925. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  57926. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  57927. }
  57928. }
  57929. // Textures
  57930. if (this._myScene.texturesEnabled) {
  57931. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  57932. this._effect.setTexture("albedoSampler", this.albedoTexture);
  57933. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  57934. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  57935. }
  57936. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  57937. this._effect.setTexture("ambientSampler", this.ambientTexture);
  57938. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  57939. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  57940. }
  57941. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  57942. this._effect.setTexture("opacitySampler", this.opacityTexture);
  57943. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  57944. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  57945. }
  57946. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  57947. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  57948. if (this.reflectionTexture.isCube) {
  57949. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  57950. }
  57951. else {
  57952. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  57953. }
  57954. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  57955. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  57956. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  57957. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  57958. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  57959. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  57960. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  57961. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  57962. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  57963. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  57964. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  57965. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  57966. }
  57967. }
  57968. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  57969. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  57970. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  57971. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  57972. }
  57973. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  57974. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  57975. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  57976. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  57977. }
  57978. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  57979. if (this.metallicTexture) {
  57980. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  57981. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  57982. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  57983. }
  57984. else if (this.reflectivityTexture) {
  57985. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  57986. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  57987. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  57988. }
  57989. }
  57990. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  57991. this._effect.setTexture("bumpSampler", this.bumpTexture);
  57992. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  57993. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  57994. }
  57995. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  57996. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  57997. var depth = 1.0;
  57998. if (this.refractionTexture.isCube) {
  57999. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58000. }
  58001. else {
  58002. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58003. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58004. if (this.refractionTexture.depth) {
  58005. depth = this.refractionTexture.depth;
  58006. }
  58007. }
  58008. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  58009. }
  58010. if ((this.reflectionTexture || this.refractionTexture)) {
  58011. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  58012. }
  58013. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58014. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  58015. }
  58016. }
  58017. // Clip plane
  58018. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  58019. // Point size
  58020. if (this.pointsCloud) {
  58021. this._effect.setFloat("pointSize", this.pointSize);
  58022. }
  58023. // Colors
  58024. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  58025. if (this._defines.METALLICWORKFLOW) {
  58026. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  58027. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  58028. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  58029. }
  58030. else {
  58031. // GAMMA CORRECTION.
  58032. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  58033. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  58034. }
  58035. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  58036. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  58037. // GAMMA CORRECTION.
  58038. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  58039. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  58040. // GAMMA CORRECTION.
  58041. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  58042. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  58043. }
  58044. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  58045. // GAMMA CORRECTION.
  58046. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  58047. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  58048. // Lights
  58049. if (this._myScene.lightsEnabled && !this.disableLighting) {
  58050. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  58051. }
  58052. // View
  58053. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  58054. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  58055. }
  58056. // Fog
  58057. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  58058. this._lightingInfos.x = this.directIntensity;
  58059. this._lightingInfos.y = this.emissiveIntensity;
  58060. this._lightingInfos.z = this.environmentIntensity;
  58061. this._lightingInfos.w = this.specularIntensity;
  58062. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  58063. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  58064. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  58065. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  58066. this._cameraInfos.x = this.cameraExposure;
  58067. this._cameraInfos.y = this.cameraContrast;
  58068. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  58069. if (this.cameraColorCurves) {
  58070. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  58071. }
  58072. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  58073. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  58074. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  58075. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  58076. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  58077. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  58078. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  58079. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  58080. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  58081. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  58082. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  58083. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  58084. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  58085. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  58086. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  58087. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  58088. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  58089. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  58090. // Log. depth
  58091. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  58092. }
  58093. _super.prototype.bind.call(this, world, mesh);
  58094. this._myScene = null;
  58095. };
  58096. PBRMaterial.prototype.getAnimatables = function () {
  58097. var results = [];
  58098. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  58099. results.push(this.albedoTexture);
  58100. }
  58101. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  58102. results.push(this.ambientTexture);
  58103. }
  58104. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  58105. results.push(this.opacityTexture);
  58106. }
  58107. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  58108. results.push(this.reflectionTexture);
  58109. }
  58110. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  58111. results.push(this.emissiveTexture);
  58112. }
  58113. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  58114. results.push(this.metallicTexture);
  58115. }
  58116. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  58117. results.push(this.reflectivityTexture);
  58118. }
  58119. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  58120. results.push(this.bumpTexture);
  58121. }
  58122. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  58123. results.push(this.lightmapTexture);
  58124. }
  58125. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  58126. results.push(this.refractionTexture);
  58127. }
  58128. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  58129. results.push(this.cameraColorGradingTexture);
  58130. }
  58131. return results;
  58132. };
  58133. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58134. if (forceDisposeTextures) {
  58135. if (this.albedoTexture) {
  58136. this.albedoTexture.dispose();
  58137. }
  58138. if (this.ambientTexture) {
  58139. this.ambientTexture.dispose();
  58140. }
  58141. if (this.opacityTexture) {
  58142. this.opacityTexture.dispose();
  58143. }
  58144. if (this.reflectionTexture) {
  58145. this.reflectionTexture.dispose();
  58146. }
  58147. if (this.emissiveTexture) {
  58148. this.emissiveTexture.dispose();
  58149. }
  58150. if (this.metallicTexture) {
  58151. this.metallicTexture.dispose();
  58152. }
  58153. if (this.reflectivityTexture) {
  58154. this.reflectivityTexture.dispose();
  58155. }
  58156. if (this.bumpTexture) {
  58157. this.bumpTexture.dispose();
  58158. }
  58159. if (this.lightmapTexture) {
  58160. this.lightmapTexture.dispose();
  58161. }
  58162. if (this.refractionTexture) {
  58163. this.refractionTexture.dispose();
  58164. }
  58165. if (this.cameraColorGradingTexture) {
  58166. this.cameraColorGradingTexture.dispose();
  58167. }
  58168. }
  58169. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58170. };
  58171. PBRMaterial.prototype.clone = function (name) {
  58172. var _this = this;
  58173. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  58174. };
  58175. PBRMaterial.prototype.serialize = function () {
  58176. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58177. serializationObject.customType = "BABYLON.PBRMaterial";
  58178. return serializationObject;
  58179. };
  58180. // Statics
  58181. PBRMaterial.Parse = function (source, scene, rootUrl) {
  58182. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  58183. };
  58184. return PBRMaterial;
  58185. }(BABYLON.Material));
  58186. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  58187. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  58188. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  58189. PBRMaterial._scaledReflection = new BABYLON.Color3();
  58190. __decorate([
  58191. BABYLON.serialize()
  58192. ], PBRMaterial.prototype, "directIntensity", void 0);
  58193. __decorate([
  58194. BABYLON.serialize()
  58195. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  58196. __decorate([
  58197. BABYLON.serialize()
  58198. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  58199. __decorate([
  58200. BABYLON.serialize()
  58201. ], PBRMaterial.prototype, "specularIntensity", void 0);
  58202. __decorate([
  58203. BABYLON.serialize()
  58204. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  58205. __decorate([
  58206. BABYLON.serialize()
  58207. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  58208. __decorate([
  58209. BABYLON.serialize()
  58210. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  58211. __decorate([
  58212. BABYLON.serialize()
  58213. ], PBRMaterial.prototype, "cameraExposure", void 0);
  58214. __decorate([
  58215. BABYLON.serialize()
  58216. ], PBRMaterial.prototype, "cameraContrast", void 0);
  58217. __decorate([
  58218. BABYLON.serializeAsTexture()
  58219. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  58220. __decorate([
  58221. BABYLON.serializeAsColorCurves()
  58222. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  58223. __decorate([
  58224. BABYLON.serializeAsColor3()
  58225. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  58226. __decorate([
  58227. BABYLON.serialize()
  58228. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  58229. __decorate([
  58230. BABYLON.serializeAsColor3()
  58231. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  58232. __decorate([
  58233. BABYLON.serialize()
  58234. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  58235. __decorate([
  58236. BABYLON.serializeAsColor3()
  58237. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  58238. __decorate([
  58239. BABYLON.serialize()
  58240. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  58241. __decorate([
  58242. BABYLON.serializeAsColor3()
  58243. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  58244. __decorate([
  58245. BABYLON.serialize()
  58246. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  58247. __decorate([
  58248. BABYLON.serializeAsColor3()
  58249. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  58250. __decorate([
  58251. BABYLON.serialize()
  58252. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  58253. __decorate([
  58254. BABYLON.serialize()
  58255. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  58256. __decorate([
  58257. BABYLON.serialize()
  58258. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  58259. __decorate([
  58260. BABYLON.serializeAsTexture()
  58261. ], PBRMaterial.prototype, "albedoTexture", void 0);
  58262. __decorate([
  58263. BABYLON.serializeAsTexture()
  58264. ], PBRMaterial.prototype, "ambientTexture", void 0);
  58265. __decorate([
  58266. BABYLON.serialize()
  58267. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  58268. __decorate([
  58269. BABYLON.serializeAsTexture()
  58270. ], PBRMaterial.prototype, "opacityTexture", void 0);
  58271. __decorate([
  58272. BABYLON.serializeAsTexture()
  58273. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  58274. __decorate([
  58275. BABYLON.serializeAsTexture()
  58276. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  58277. __decorate([
  58278. BABYLON.serializeAsTexture()
  58279. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  58280. __decorate([
  58281. BABYLON.serializeAsTexture()
  58282. ], PBRMaterial.prototype, "metallicTexture", void 0);
  58283. __decorate([
  58284. BABYLON.serialize()
  58285. ], PBRMaterial.prototype, "metallic", void 0);
  58286. __decorate([
  58287. BABYLON.serialize()
  58288. ], PBRMaterial.prototype, "roughness", void 0);
  58289. __decorate([
  58290. BABYLON.serializeAsTexture()
  58291. ], PBRMaterial.prototype, "bumpTexture", void 0);
  58292. __decorate([
  58293. BABYLON.serializeAsTexture()
  58294. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  58295. __decorate([
  58296. BABYLON.serializeAsTexture()
  58297. ], PBRMaterial.prototype, "refractionTexture", void 0);
  58298. __decorate([
  58299. BABYLON.serializeAsColor3("ambient")
  58300. ], PBRMaterial.prototype, "ambientColor", void 0);
  58301. __decorate([
  58302. BABYLON.serializeAsColor3("albedo")
  58303. ], PBRMaterial.prototype, "albedoColor", void 0);
  58304. __decorate([
  58305. BABYLON.serializeAsColor3("reflectivity")
  58306. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  58307. __decorate([
  58308. BABYLON.serializeAsColor3("reflection")
  58309. ], PBRMaterial.prototype, "reflectionColor", void 0);
  58310. __decorate([
  58311. BABYLON.serializeAsColor3("emissive")
  58312. ], PBRMaterial.prototype, "emissiveColor", void 0);
  58313. __decorate([
  58314. BABYLON.serialize()
  58315. ], PBRMaterial.prototype, "microSurface", void 0);
  58316. __decorate([
  58317. BABYLON.serialize()
  58318. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  58319. __decorate([
  58320. BABYLON.serialize()
  58321. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  58322. __decorate([
  58323. BABYLON.serializeAsFresnelParameters()
  58324. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  58325. __decorate([
  58326. BABYLON.serializeAsFresnelParameters()
  58327. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  58328. __decorate([
  58329. BABYLON.serialize()
  58330. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  58331. __decorate([
  58332. BABYLON.serialize()
  58333. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  58334. __decorate([
  58335. BABYLON.serialize()
  58336. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  58337. __decorate([
  58338. BABYLON.serialize()
  58339. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  58340. __decorate([
  58341. BABYLON.serialize()
  58342. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  58343. __decorate([
  58344. BABYLON.serialize()
  58345. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  58346. __decorate([
  58347. BABYLON.serialize()
  58348. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  58349. __decorate([
  58350. BABYLON.serialize()
  58351. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  58352. __decorate([
  58353. BABYLON.serialize()
  58354. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  58355. __decorate([
  58356. BABYLON.serialize()
  58357. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  58358. __decorate([
  58359. BABYLON.serialize()
  58360. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  58361. __decorate([
  58362. BABYLON.serialize()
  58363. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  58364. __decorate([
  58365. BABYLON.serialize()
  58366. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  58367. __decorate([
  58368. BABYLON.serialize()
  58369. ], PBRMaterial.prototype, "useParallax", void 0);
  58370. __decorate([
  58371. BABYLON.serialize()
  58372. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  58373. __decorate([
  58374. BABYLON.serialize()
  58375. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  58376. __decorate([
  58377. BABYLON.serialize()
  58378. ], PBRMaterial.prototype, "disableLighting", void 0);
  58379. __decorate([
  58380. BABYLON.serialize()
  58381. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  58382. __decorate([
  58383. BABYLON.serialize()
  58384. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  58385. __decorate([
  58386. BABYLON.serialize()
  58387. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  58388. __decorate([
  58389. BABYLON.serialize()
  58390. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  58391. BABYLON.PBRMaterial = PBRMaterial;
  58392. })(BABYLON || (BABYLON = {}));
  58393. //# sourceMappingURL=babylon.pbrMaterial.js.map
  58394. var BABYLON;
  58395. (function (BABYLON) {
  58396. var DebugLayer = (function () {
  58397. function DebugLayer(scene) {
  58398. this._scene = scene;
  58399. }
  58400. /** Creates the inspector window. */
  58401. DebugLayer.prototype._createInspector = function (popup) {
  58402. if (!this._inspector) {
  58403. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  58404. } // else nothing to do,; instance is already existing
  58405. };
  58406. DebugLayer.prototype.isVisible = function () {
  58407. if (!this._inspector) {
  58408. return false;
  58409. }
  58410. return true;
  58411. };
  58412. DebugLayer.prototype.hide = function () {
  58413. if (this._inspector) {
  58414. this._inspector.dispose();
  58415. this._inspector = null;
  58416. }
  58417. };
  58418. DebugLayer.prototype.show = function (popup) {
  58419. if (typeof INSPECTOR == 'undefined') {
  58420. // Load inspector and add it to the DOM
  58421. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  58422. }
  58423. else {
  58424. // Otherwise creates the inspector
  58425. this._createInspector(popup);
  58426. }
  58427. };
  58428. return DebugLayer;
  58429. }());
  58430. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  58431. BABYLON.DebugLayer = DebugLayer;
  58432. })(BABYLON || (BABYLON = {}));
  58433. //# sourceMappingURL=babylon.debugLayer.js.map
  58434. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  58435. var BABYLON;
  58436. (function (BABYLON) {
  58437. var StandardRenderingPipeline = (function (_super) {
  58438. __extends(StandardRenderingPipeline, _super);
  58439. /**
  58440. * @constructor
  58441. * @param {string} name - The rendering pipeline name
  58442. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58443. * @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)
  58444. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58445. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58446. */
  58447. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58448. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58449. var _this = _super.call(this, scene.getEngine(), name) || this;
  58450. _this.downSampleX4PostProcess = null;
  58451. _this.brightPassPostProcess = null;
  58452. _this.gaussianBlurHPostProcesses = [];
  58453. _this.gaussianBlurVPostProcesses = [];
  58454. _this.textureAdderPostProcess = null;
  58455. _this.textureAdderFinalPostProcess = null;
  58456. _this.lensFlareFinalPostProcess = null;
  58457. _this.lensFlarePostProcess = null;
  58458. _this.lensFlareComposePostProcess = null;
  58459. _this.depthOfFieldPostProcess = null;
  58460. // Values
  58461. _this.brightThreshold = 1.0;
  58462. _this.blurWidth = 2.0;
  58463. _this.horizontalBlur = false;
  58464. _this.gaussianCoefficient = 0.25;
  58465. _this.gaussianMean = 1.0;
  58466. _this.gaussianStandardDeviation = 1.0;
  58467. _this.exposure = 1.0;
  58468. _this.lensTexture = null;
  58469. _this.lensColorTexture = null;
  58470. _this.lensFlareStrength = 20.0;
  58471. _this.lensFlareGhostDispersal = 1.4;
  58472. _this.lensFlareHaloWidth = 0.7;
  58473. _this.lensFlareDistortionStrength = 16.0;
  58474. _this.lensStarTexture = null;
  58475. _this.lensFlareDirtTexture = null;
  58476. _this.depthOfFieldDistance = 10.0;
  58477. _this.depthOfFieldBlurWidth = 2.0;
  58478. // IAnimatable
  58479. _this.animations = [];
  58480. _this._depthRenderer = null;
  58481. _this._currentDepthOfFieldSource = null;
  58482. // Getters and setters
  58483. _this._depthOfFieldEnabled = true;
  58484. _this._lensFlareEnabled = true;
  58485. // Initialize
  58486. _this._scene = scene;
  58487. // Create pass post-processe
  58488. if (!originalPostProcess) {
  58489. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  58490. }
  58491. else {
  58492. _this.originalPostProcess = originalPostProcess;
  58493. }
  58494. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58495. // Create down sample X4 post-process
  58496. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  58497. // Create bright pass post-process
  58498. _this._createBrightPassPostProcess(scene, ratio / 2);
  58499. // Create gaussian blur post-processes (down sampling blurs)
  58500. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  58501. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  58502. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  58503. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  58504. // Create texture adder post-process
  58505. _this._createTextureAdderPostProcess(scene, ratio);
  58506. // Create depth-of-field source post-process
  58507. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58508. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58509. // Create lens flare post-process
  58510. _this._createLensFlarePostProcess(scene, ratio);
  58511. // Create depth-of-field source post-process post lens-flare and disable it now
  58512. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58513. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58514. // Create gaussian blur used by depth-of-field
  58515. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  58516. // Create depth-of-field post-process
  58517. _this._createDepthOfFieldPostProcess(scene, ratio);
  58518. // Finish
  58519. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58520. if (cameras !== null) {
  58521. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58522. }
  58523. // Deactivate
  58524. _this.LensFlareEnabled = false;
  58525. _this.DepthOfFieldEnabled = false;
  58526. return _this;
  58527. }
  58528. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58529. get: function () {
  58530. return this._depthOfFieldEnabled;
  58531. },
  58532. set: function (enabled) {
  58533. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  58534. if (enabled && !this._depthOfFieldEnabled) {
  58535. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  58536. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  58537. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  58538. this._depthRenderer = this._scene.enableDepthRenderer();
  58539. }
  58540. else if (!enabled && this._depthOfFieldEnabled) {
  58541. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  58542. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  58543. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  58544. }
  58545. this._depthOfFieldEnabled = enabled;
  58546. },
  58547. enumerable: true,
  58548. configurable: true
  58549. });
  58550. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58551. get: function () {
  58552. return this._lensFlareEnabled;
  58553. },
  58554. set: function (enabled) {
  58555. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  58556. if (enabled && !this._lensFlareEnabled) {
  58557. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  58558. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  58559. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  58560. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  58561. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  58562. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  58563. }
  58564. else if (!enabled && this._lensFlareEnabled) {
  58565. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  58566. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  58567. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  58568. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  58569. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  58570. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  58571. }
  58572. this._lensFlareEnabled = enabled;
  58573. },
  58574. enumerable: true,
  58575. configurable: true
  58576. });
  58577. // Sets depth-of-field save post-process
  58578. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  58579. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  58580. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  58581. switch (name) {
  58582. case "HDRBaseDepthOfFieldSource":
  58583. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  58584. break;
  58585. case "HDRPostLensFlareDepthOfFieldSource":
  58586. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  58587. break;
  58588. default: break;
  58589. }
  58590. };
  58591. // Down Sample X4 Post-Processs
  58592. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58593. var _this = this;
  58594. var downSampleX4Offsets = new Array(32);
  58595. 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);
  58596. this.downSampleX4PostProcess.onApply = function (effect) {
  58597. var id = 0;
  58598. for (var i = -2; i < 2; i++) {
  58599. for (var j = -2; j < 2; j++) {
  58600. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  58601. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  58602. id += 2;
  58603. }
  58604. }
  58605. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58606. };
  58607. // Add to pipeline
  58608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58609. };
  58610. // Brightpass Post-Process
  58611. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58612. var _this = this;
  58613. var brightOffsets = new Array(8);
  58614. 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);
  58615. this.brightPassPostProcess.onApply = function (effect) {
  58616. var sU = (1.0 / _this.brightPassPostProcess.width);
  58617. var sV = (1.0 / _this.brightPassPostProcess.height);
  58618. brightOffsets[0] = -0.5 * sU;
  58619. brightOffsets[1] = 0.5 * sV;
  58620. brightOffsets[2] = 0.5 * sU;
  58621. brightOffsets[3] = 0.5 * sV;
  58622. brightOffsets[4] = -0.5 * sU;
  58623. brightOffsets[5] = -0.5 * sV;
  58624. brightOffsets[6] = 0.5 * sU;
  58625. brightOffsets[7] = -0.5 * sV;
  58626. effect.setArray2("dsOffsets", brightOffsets);
  58627. effect.setFloat("brightThreshold", _this.brightThreshold);
  58628. };
  58629. // Add to pipeline
  58630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58631. };
  58632. // Create gaussian blur H&V post-processes
  58633. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58634. var _this = this;
  58635. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58636. var blurOffsets = new Array(9);
  58637. var blurWeights = new Array(9);
  58638. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  58639. var callback = function (height) {
  58640. return function (effect) {
  58641. // Weights
  58642. var x = 0.0;
  58643. for (var i = 0; i < 9; i++) {
  58644. x = (i - 4.0) / 4.0;
  58645. blurWeights[i] =
  58646. _this.gaussianCoefficient
  58647. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  58648. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  58649. }
  58650. var lastOutputDimensions = {
  58651. width: scene.getEngine().getRenderWidth(),
  58652. height: scene.getEngine().getRenderHeight()
  58653. };
  58654. for (var i = 0; i < 9; i++) {
  58655. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  58656. blurOffsets[i] = value;
  58657. }
  58658. effect.setArray("blurOffsets", blurOffsets);
  58659. effect.setArray("blurWeights", blurWeights);
  58660. if (height) {
  58661. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  58662. }
  58663. else {
  58664. effect.setFloat("blurWidth", _this[blurWidthKey]);
  58665. }
  58666. };
  58667. };
  58668. // Create horizontal gaussian blur post-processes
  58669. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58670. gaussianBlurHPostProcess.onApply = callback(false);
  58671. // Create vertical gaussian blur post-process
  58672. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58673. gaussianBlurVPostProcess.onApply = callback(true);
  58674. // Add to pipeline
  58675. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  58676. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  58677. // Finish
  58678. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  58679. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  58680. };
  58681. // Create texture adder post-process
  58682. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58683. var _this = this;
  58684. 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);
  58685. this.textureAdderPostProcess.onApply = function (effect) {
  58686. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  58687. effect.setTexture("lensSampler", _this.lensTexture);
  58688. effect.setFloat("exposure", _this.exposure);
  58689. };
  58690. // Add to pipeline
  58691. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58692. };
  58693. // Create lens flare post-process
  58694. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58695. var _this = this;
  58696. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58697. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58698. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  58699. 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);
  58700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58701. var resolution = new BABYLON.Vector2(0, 0);
  58702. // Lens flare
  58703. this.lensFlarePostProcess.onApply = function (effect) {
  58704. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  58705. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58706. effect.setFloat("strength", _this.lensFlareStrength);
  58707. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58708. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58709. // Shift
  58710. resolution.x = _this.lensFlarePostProcess.width;
  58711. resolution.y = _this.lensFlarePostProcess.height;
  58712. effect.setVector2("resolution", resolution);
  58713. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58714. };
  58715. // Compose
  58716. 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);
  58717. 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);
  58718. this.lensFlareComposePostProcess.onApply = function (effect) {
  58719. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  58720. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58721. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58722. // Lens start rotation matrix
  58723. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58724. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58725. 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));
  58726. camRot *= 4.0;
  58727. 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);
  58728. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58729. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58730. };
  58731. };
  58732. // Create depth-of-field post-process
  58733. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58734. var _this = this;
  58735. 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);
  58736. this.depthOfFieldPostProcess.onApply = function (effect) {
  58737. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58738. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  58739. effect.setFloat("distance", _this.depthOfFieldDistance);
  58740. };
  58741. // Add to pipeline
  58742. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58743. };
  58744. // Dispose
  58745. StandardRenderingPipeline.prototype.dispose = function () {
  58746. for (var i = 0; i < this._scene.cameras.length; i++) {
  58747. var camera = this._scene.cameras[i];
  58748. this.originalPostProcess.dispose(camera);
  58749. this.downSampleX4PostProcess.dispose(camera);
  58750. this.brightPassPostProcess.dispose(camera);
  58751. this.textureAdderPostProcess.dispose(camera);
  58752. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  58753. this.gaussianBlurHPostProcesses[j].dispose(camera);
  58754. }
  58755. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  58756. this.gaussianBlurVPostProcesses[j].dispose(camera);
  58757. }
  58758. this.textureAdderFinalPostProcess.dispose(camera);
  58759. this.lensFlarePostProcess.dispose(camera);
  58760. this.lensFlareComposePostProcess.dispose(camera);
  58761. this.depthOfFieldPostProcess.dispose(camera);
  58762. }
  58763. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58764. _super.prototype.dispose.call(this);
  58765. };
  58766. // Serialize rendering pipeline
  58767. StandardRenderingPipeline.prototype.serialize = function () {
  58768. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58769. serializationObject.customType = "StandardRenderingPipeline";
  58770. return serializationObject;
  58771. };
  58772. // Parse serialized pipeline
  58773. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58774. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58775. };
  58776. return StandardRenderingPipeline;
  58777. }(BABYLON.PostProcessRenderPipeline));
  58778. __decorate([
  58779. BABYLON.serialize()
  58780. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58781. __decorate([
  58782. BABYLON.serialize()
  58783. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58784. __decorate([
  58785. BABYLON.serialize()
  58786. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58787. __decorate([
  58788. BABYLON.serialize()
  58789. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  58790. __decorate([
  58791. BABYLON.serialize()
  58792. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  58793. __decorate([
  58794. BABYLON.serialize()
  58795. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  58796. __decorate([
  58797. BABYLON.serialize()
  58798. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58799. __decorate([
  58800. BABYLON.serializeAsTexture("lensTexture")
  58801. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58802. __decorate([
  58803. BABYLON.serializeAsTexture("lensColorTexture")
  58804. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58805. __decorate([
  58806. BABYLON.serialize()
  58807. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58808. __decorate([
  58809. BABYLON.serialize()
  58810. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58811. __decorate([
  58812. BABYLON.serialize()
  58813. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58814. __decorate([
  58815. BABYLON.serialize()
  58816. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58817. __decorate([
  58818. BABYLON.serializeAsTexture("lensStarTexture")
  58819. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58820. __decorate([
  58821. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58822. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58823. __decorate([
  58824. BABYLON.serialize()
  58825. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58826. __decorate([
  58827. BABYLON.serialize()
  58828. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58829. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58830. })(BABYLON || (BABYLON = {}));
  58831. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58832. 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}"};
  58833. 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"};
  58834. 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(e){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(o){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.set=function(t,i,r){return this.copyFromFloats(t,i,r)},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.copyFromFloats=function(t,i,r,n){return this.r=t,this.g=i,this.b=r,this.a=n,this},t.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.set=function(t,i){return this.copyFromFloats(t,i)},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.prototype.set=function(t,i,r){return this.copyFromFloats(t,i,r)},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r(-1,0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.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=A.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.prototype.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.set=function(t,i){return this.copyFromFloats(t,i)},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.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.set=function(t,i,r,n){return this.copyFromFloats(t,i,r,n)},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.IsIdentity=function(t){return t&&0===t.x&&0===t.y&&0===t.z&&1===t.w},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=A.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),F=e*w-s*d+a*R,M=-(e*v-s*g+h*R),A=1/(i*T+r*_+n*F+o*M),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,N=e*y-h*u,D=e*m-s*u;return t.m[0]=T*A,t.m[4]=_*A,t.m[8]=F*A,t.m[12]=M*A,t.m[1]=-(r*z-n*w+o*v)*A,t.m[5]=(i*z-n*d+o*g)*A,t.m[9]=-(i*w-r*d+o*R)*A,t.m[13]=(i*v-r*g+n*R)*A,t.m[2]=(r*b-n*L+o*C)*A,t.m[6]=-(i*b-n*P+o*Z)*A,t.m[10]=(i*L-r*P+o*S)*A,t.m[14]=-(i*C-r*Z+n*S)*A,t.m[3]=-(r*I-n*H+o*V)*A,t.m[7]=(i*I-n*q+o*N)*A,t.m[11]=-(i*H-r*q+o*D)*A,t.m[15]=(i*V-r*N+n*D)*A,this},r.prototype.setTranslationFromFloats=function(t,i,r){return this.m[12]=t,this.m[13]=i,this.m[14]=r,\nthis},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.getTranslationToRef=function(t){return t.x=this.m[12],t.y=this.m[13],t.z=this.m[14],this},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];return 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],F=t.m[6],M=t.m[7],A=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*A+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*F+e*L+s*S,i[r+3]=n*R+o*M+e*C+s*I,i[r+4]=h*v+a*T+u*A+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*F+u*L+m*S,i[r+7]=h*R+a*M+u*C+m*I,i[r+8]=y*v+c*T+p*A+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*F+p*L+f*S,i[r+11]=y*R+c*M+p*C+f*I,i[r+12]=x*v+l*T+z*A+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*F+z*L+w*S,i[r+15]=x*R+l*M+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,A.Matrix[0]),a.FromRotationMatrixToRef(A.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,A.Matrix[1]),i.toRotationMatrix(A.Matrix[0]),A.Matrix[1].multiplyToRef(A.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=!1);var e=o?-1:1,s=Math.tan(t.upDegrees*Math.PI/180),h=Math.tan(t.downDegrees*Math.PI/180),a=Math.tan(t.leftDegrees*Math.PI/180),u=Math.tan(t.rightDegrees*Math.PI/180),m=2/(a+u),y=2/(s+h);n.m[0]=m,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=y,n.m[6]=n.m[7]=0,n.m[8]=(a-u)*m*.5*e,n.m[9]=-((s-h)*y*.5)*e,n.m[10]=-(i+r)/(r-i)*e,n.m[11]=1*e,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\",t[t.BONE=2]=\"BONE\"}(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 F=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=F;var M=function(){function t(){}return t}();M.Color3=[r.Black(),r.Black(),r.Black()],M.Vector2=[o.Zero(),o.Zero(),o.Zero()],M.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],M.Vector4=[s.Zero(),s.Zero(),s.Zero()],M.Quaternion=[a.Zero(),a.Zero()],M.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=M;var A=function(){function t(){}return t}();A.Vector3=[e.Zero()],A.Matrix=[u.Zero(),u.Zero()],A.Quaternion=[a.Zero()]}(BABYLON||(BABYLON={}));";
  58835. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  58836. module.exports = BABYLON;
  58837. };